在Python中使用哪个更好?Time.clock()还是time.time()?哪一种更准确?

例如:

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

vs.

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

当前回答

time.clock()在Python 3.8中被移除,因为它具有平台相关的行为:

在Unix上,返回以秒表示的浮点数形式的当前处理器时间。 在Windows上,此函数以浮点数的形式返回自第一次调用该函数以来经过的时钟秒数 打印(time.clock ());time . sleep (10);print (time.clock ()) # Linux: 0.0382 0.0384 #参见处理器时间 # Windows: 26.1224 36.1566 #见clock Time

那么选择哪个函数呢?

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this. Use time.process_time() Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time. Use time.perf_counter() time.time() also measures wall-clock time but can be reset, so you could go back in time time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()

其他回答

这种差异是平台特有的。

例如,clock()在Windows上与Linux上有很大不同。

对于您描述的这类示例,您可能希望使用"timeit"模块。

简单回答:在Python中使用time.clock()进行计时。

在*nix系统上,clock()返回处理器时间为浮点数,以秒表示。在Windows上,它以浮点数的形式返回自第一次调用此函数以来所经过的秒数。

time()返回自纪元以来的秒数,以UTC为单位,作为浮点数。不能保证您将获得比1秒更好的精度(即使time()返回一个浮点数)。还要注意,如果在两次调用该函数之间设置了系统时钟,那么第二次函数调用将返回一个较低的值。

正如其他人所注意到的,time.clock()已被弃用,取而代之的是time.perf_counter()或time.process_time(),但Python 3.7通过time.perf_counter_ns()、time.process_time_ns()和time.time_ns()以及其他3个函数引入了纳秒分辨率计时。

PEP 564中详细介绍了这6个新的纳秒分辨率函数:

time.clock_gettime_ns (clock_id) 时间。clock_settime_ns (clock_id、时间:int) time.monotonic_ns () time.perf_counter_ns () time.process_time_ns () time.time_ns () 这些函数类似于没有_ns后缀的版本,但是 返回一个纳秒数作为Python int。

正如其他人也注意到的那样,使用timeit模块为函数和小代码段计时。

在Linux上,time()比clock()具有更好的精度。Clock()的精度小于10毫秒。而time()提供完美的精度。 我的测试用的是CentOS 6.4和python 2.6

using time():

1 requests, response time: 14.1749382019 ms
2 requests, response time: 8.01301002502 ms
3 requests, response time: 8.01491737366 ms
4 requests, response time: 8.41021537781 ms
5 requests, response time: 8.38804244995 ms

使用时钟():

1 requests, response time: 10.0 ms
2 requests, response time: 0.0 ms 
3 requests, response time: 0.0 ms
4 requests, response time: 10.0 ms
5 requests, response time: 0.0 ms 
6 requests, response time: 0.0 ms
7 requests, response time: 0.0 ms 
8 requests, response time: 0.0 ms

其他人回答了re: time.time() vs. time.clock()。

但是,如果您是为了基准测试/分析目的而对代码块的执行进行计时,则应该查看timeit模块。