Python的time.clock()与time.time()的准确性?

2024-04-20 07:53:16 发布

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

在Python中,哪个更好地用于计时?time.clock()或time.time()?哪一个更准确?

例如:

start = time.clock()
... do something
elapsed = (time.clock() - start)

start = time.time()
... do something
elapsed = (time.time() - start)

Tags: timedostartsomething计时clockelapsed
3条回答

简单的回答是:大多数时候time.clock()会更好。 但是,如果您正在为某些硬件计时(例如,您在GPU中放入的某个算法),那么time.clock()将摆脱这一次,而time.time()是唯一剩下的解决方案。

注意:无论使用什么方法,计时将取决于您无法控制的因素(进程何时切换,切换频率,…),这对于time.time()来说更糟,但对于time.clock()来说也存在,因此您不应只运行一个计时测试,而应始终运行一系列测试并查看时间的平均值/方差。

从3.3开始,time.clock() is deprecated,建议改用time.process_time()time.perf_counter()

之前在2.7中,根据time module docs

time.clock()

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, but in any case, this is the function to use for benchmarking Python or timing algorithms.

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.

此外,还有用于基准代码段的timeit模块。

Others回答了re:time.time()time.clock()

但是,如果您正为基准测试/分析目的对代码块的执行进行计时,则应该查看^{} module

相关问题 更多 >