gpt4 book ai didi

python - 如何在 Python 中测量耗时?

转载 作者:IT老高 更新时间:2023-10-28 11:58:25 25 4
gpt4 key购买 nike

我想测量执行一个函数所花费的时间。我无法让 timeit 工作:

import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)

最佳答案

使用 time.time()测量两点之间经过的挂钟时间:

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

这给出了以秒为单位的执行时间。


自 Python 3.3 以来的另一个选择可能是使用 perf_counterprocess_time , 取决于你的要求。 3.3之前推荐使用time.clock (感谢 Amber)。但是,它目前已被弃用:

On Unix, return the current processor time as a floating point numberexpressed in seconds. The precision, and in fact the very definitionof the meaning of “processor time”, depends on that of the C functionof the same name.

On Windows, this function returns wall-clock seconds elapsed since thefirst call to this function, as a floating point number, based on theWin32 function QueryPerformanceCounter(). The resolution is typicallybetter than one microsecond.

Deprecated since version 3.3: The behaviour of this function dependson the platform: use perf_counter() or process_time() instead,depending on your requirements, to have a well defined behaviour.

关于python - 如何在 Python 中测量耗时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370801/

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