OpenAI Cookbook 前天 02:18
No Title
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文通过调用Python、C++和Java的排序函数,对一组包含随机整数的数组进行了10次排序测试。实验旨在衡量不同编程语言在处理相同排序任务时的性能差异,并以毫秒为单位记录各语言的平均排序时间。通过对比这些时间数据,可以直观了解Python、C++和Java在数组排序方面的效率表现,为开发者在实际应用中选择合适的语言提供参考。

💡 **Python数组排序效率**:Python通过调用内置的sort()方法对数组进行排序,并在循环中执行10次以测量平均性能。测试结果以毫秒为单位显示,为评估Python在数值计算和数据处理方面的速度提供了一个基准。

💡 **C++数组排序性能**:C++利用std::sort函数对vector中的数组进行排序,并使用chrono库精确计时。代码在循环中执行10次排序操作,最终输出总耗时(毫秒),展示了C++作为编译型语言在排序操作上的原生效率。

💡 **Java数组排序速度**:Java通过Arrays.sort()方法对数组进行排序,并利用System.nanoTime()获取高精度时间戳来计算排序耗时。同样执行10次排序并转换为毫秒输出,以衡量Java在处理大规模数据排序时的表现。

💡 **多语言性能对比**:通过对Python、C++和Java的排序时间进行直接比较,可以清晰地看到它们在执行相同排序任务时的速度差异。通常情况下,C++和Java作为编译型语言会比Python(解释型语言)具有更高的执行效率,尤其是在处理大量数据时。

from openai import OpenAIfrom typing import List, OptionalMODEL_NAME = "gpt-5"# Tools that will be passed to every model invocation. They are defined once so# that the configuration lives in a single place.TOOLS = [    {        "type": "custom",        "name": "code_exec_python",        "description": "Executes python code",    },    {        "type": "custom",        "name": "code_exec_cpp",        "description": "Executes c++ code",    },    {        "type": "custom",        "name": "code_exec_java",        "description": "Executes java code",    },]client = OpenAI()def create_response(    input_messages: List[dict],    previous_response_id: Optional[str] = None,):    """Wrapper around ``client.responses.create``.    Parameters    ----------    input_messages: List[dict]        The running conversation history to feed to the model.    previous_response_id: str | None        Pass the ``response.id`` from the *previous* call so the model can keep        the thread of the conversation.  Omit on the very first request.    """    kwargs = {        "model": MODEL_NAME,        "input": input_messages,        "text": {"format": {"type": "text"}},        "tools": TOOLS,    }    if previous_response_id:        kwargs["previous_response_id"] = previous_response_id    return client.responses.create(**kwargs)# Recursive def run_conversation(    input_messages: List[dict],    previous_response_id: Optional[str] = None,):      response = create_response(input_messages, previous_response_id)    # ``response.output`` is expected to be a list where element 0 is the model    # message.  Element 1 (if present) denotes a tool call.  When the model is    # done with tool calls, that element is omitted.    tool_call = response.output[1] if len(response.output) > 1 else None    if tool_call and tool_call.type == "custom_tool_call":        print("--- tool name ---")        print(tool_call.name)        print("--- tool call argument (generated code) ---")        print(tool_call.input)                # Add a synthetic *tool result* so the model can continue the thread.                input_messages.append(            {                "type": "function_call_output",                "call_id": tool_call.call_id,                "output": "done", # <-- replace with the result of the tool call            }        )        # Recurse with updated conversation and track the response id so the        # model is aware of the prior turn.        return run_conversation(input_messages, previous_response_id=response.id)    else:        # Base-case: no further tool call - return.         return prompt = """Write code to sort the array of numbers in three languages: C++, Python and Java (10 times each)using code_exec functions.ALWAYS CALL THESE THREE FUNCTIONS EXACTLY ONCE: code_exec_python, code_exec_cpp and code_exec_java tools to sort the array in each language. Stop once you've called these three functions in each language once.Print only the time it takes to sort the array in milliseconds. [448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949]"""# Initial developer message.messages = [    {        "role": "developer",        "content": prompt,    }]run_conversation(messages)
--- tool name ---code_exec_python--- tool call argument (generated code) ---import timearr = [448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949]start = time.perf_counter()for _ in range(10):    b = arr[:]  # copy    b.sort()elapsed_ms = int((time.perf_counter() - start) * 1000)print(elapsed_ms, end="")--- tool name ---code_exec_cpp--- tool call argument (generated code) ---#include <iostream>#include <vector>#include <algorithm>#include <chrono>using namespace std;int main() {    vector<int> a = {448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949};    auto start = chrono::high_resolution_clock::now();    for (int i = 0; i < 10; ++i) {        auto b = a;        sort(b.begin(), b.end());    }    auto end = chrono::high_resolution_clock::now();    auto ms = chrono::duration_cast<chrono::milliseconds>(end - start).count();    cout << ms;    return 0;}--- tool name ---code_exec_java--- tool call argument (generated code) ---import java.util.*;public class Main {    public static void main(String[] args) {        int[] a = new int[] {448, 986, 255, 884, 632, 623, 246, 439, 936, 925, 644, 159, 777, 986, 706, 723, 534, 862, 195, 686, 846, 880, 970, 276, 613, 736, 329, 622, 870, 284, 945, 708, 267, 327, 678, 807, 687, 890, 907, 645, 364, 333, 385, 262, 730, 603, 945, 358, 923, 930, 761, 504, 870, 561, 517, 928, 994, 949, 233, 137, 670, 555, 149, 870, 997, 809, 180, 498, 914, 508, 411, 378, 394, 368, 766, 486, 757, 319, 338, 159, 585, 934, 654, 194, 542, 188, 934, 163, 889, 736, 792, 737, 667, 772, 198, 971, 459, 402, 989, 949};        long start = System.nanoTime();        for (int i = 0; i < 10; i++) {            int[] b = Arrays.copyOf(a, a.length);            Arrays.sort(b);        }        long elapsedMs = (System.nanoTime() - start) / 1_000_000L;        System.out.print(elapsedMs);    }}

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Python C++ Java 数组排序 性能测试
相关文章