在Python中使用哪个更好?Time.clock()还是time.time()?哪一种更准确?
例如:
start = time.clock()
... do something
elapsed = (time.clock() - start)
vs.
start = time.time()
... do something
elapsed = (time.time() - start)
在Python中使用哪个更好?Time.clock()还是time.time()?哪一种更准确?
例如:
start = time.clock()
... do something
elapsed = (time.clock() - start)
vs.
start = time.time()
... do something
elapsed = (time.time() - start)
当前回答
从3.3开始,time.clock()已弃用,建议使用time.process_time()或time.perf_counter()。
在2.7之前,根据time模块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模块用于对代码段进行基准测试。
其他回答
我使用这段代码来比较2种方法。我的操作系统是windows 8,处理器核心i5, RAM 4GB
import time
def t_time():
start=time.time()
time.sleep(0.1)
return (time.time()-start)
def t_clock():
start=time.clock()
time.sleep(0.1)
return (time.clock()-start)
counter_time=0
counter_clock=0
for i in range(1,100):
counter_time += t_time()
for i in range(1,100):
counter_clock += t_clock()
print "time() =",counter_time/100
print "clock() =",counter_clock/100
输出:
time() = 0.0993799996376
clock() = 0.0993572257367
其他人回答了re: time.time() vs. time.clock()。
但是,如果您是为了基准测试/分析目的而对代码块的执行进行计时,则应该查看timeit模块。
从3.3开始,time.clock()已弃用,建议使用time.process_time()或time.perf_counter()。
在2.7之前,根据time模块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模块用于对代码段进行基准测试。
简单回答:在Python中使用time.clock()进行计时。
在*nix系统上,clock()返回处理器时间为浮点数,以秒表示。在Windows上,它以浮点数的形式返回自第一次调用此函数以来所经过的秒数。
time()返回自纪元以来的秒数,以UTC为单位,作为浮点数。不能保证您将获得比1秒更好的精度(即使time()返回一个浮点数)。还要注意,如果在两次调用该函数之间设置了系统时钟,那么第二次函数调用将返回一个较低的值。
在Unix上,time.clock()测量当前进程已使用的CPU时间量,因此它不适用于测量从过去某个点开始的流逝时间。在Windows上,它将测量自第一次调用函数以来所经过的时钟秒数。在任意一个系统上,time.time()将返回自epoch以来经过的秒数。
如果您正在编写仅用于Windows的代码,则两者都可以工作(尽管您将使用不同的方法- time.clock()不需要减法)。如果要在Unix系统上运行,或者您想要保证可移植的代码,则需要使用time.time()。