在Python中测量经过的时间

2024-04-27 04:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要的是开始计算代码中某个地方的时间,然后得到传递的时间,以测量执行很少的函数所花费的时间。我想我使用timeit模块是错的,但是文档对我来说太混乱了。

import timeit

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

Tags: 模块函数代码文档importhello地方时间
3条回答

如果只想测量两点之间经过的挂钟时间,可以使用^{}

import time

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

这将以秒为单位提供执行时间。

3.3之后的另一个选项可能是使用^{}^{},这取决于您的需求。在3.3之前,建议使用^{}(谢谢Amber)。但是,目前不赞成:

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

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

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

仅限Python 3:

由于time.clock()is deprecated as of Python 3.3,您将希望使用^{}进行系统范围的计时,或使用^{}进行进程范围的计时,就像您以前使用time.clock()的方式一样:

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t

新函数process_time将不包括睡眠期间经过的时间。

使用timeit.default_timer而不是timeit.timeit。前者自动提供平台和Python版本上可用的最佳时钟:

from timeit import default_timer as timer

start = timer()
# ...
end = timer()
print(end - start) # Time in seconds, e.g. 5.38091952400282

timeit.default_timer分配给time.time()或time.clock(),具体取决于操作系统。在Python 3.3上,default_timer在所有平台上都是time.perf_counter()。见Python - time.clock() vs. time.time() - accuracy?

另见:

相关问题 更多 >