gpt4 book ai didi

python - 如何作为 Python 代码(不是来自终端)分别测量函数的 CPU 运行时间和挂钟运行时间?

转载 作者:行者123 更新时间:2023-11-28 22:53:39 24 4
gpt4 key购买 nike

我正在寻找一种方法来衡量 Python 中的函数性能,将挂钟时间和 CPU 时间分开。

我研究过 python 分析器,但它们似乎是设计用来扫描程序的,而不是单独运行的。来自 http://docs.python.org/2/library/profile.html :

Note The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is timeit for reasonably accurate results). This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one.

然后我尝试了 timeit 模块:http://docs.python.org/2/library/timeit.html ,但它似乎不支持分离 CPU 和挂钟时间。据我了解,它只是测量总运行时间。

我正在寻找的是这样的:

$ time python yourprogram.py

real 0m1.028s
user 0m0.001s
sys 0m0.003s

但是我需要从 python 代码调用它,而不是从命令行调用它。

类似于 R 中的 system.time():

print(system.time(replicate(repeats, factorialRecursive(150))))
user system elapsed
0.041 0.001 0.041

如何在 Python 中实现这一点?

最佳答案

The resource module包含 getrusage,它应该允许您分别检索用户、系统和挂钟时间,就像 time 命令一样。

关于python - 如何作为 Python 代码(不是来自终端)分别测量函数的 CPU 运行时间和挂钟运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com