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

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

在Python中使用哪个计时更好?time.clock()或time.time()?哪一个提供更高的准确性?

例如:

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

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

Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?

for example:

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

vs.

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

回答 0

作为3.3,time.clock()已被弃用,并且它建议使用time.process_time()time.perf_counter()来代替。

于2.7,根据时间模块docs

time.clock()

在Unix上,以秒为单位返回当前处理器时间,以浮点数表示。精度(实际上是“处理器时间”的含义的确切定义)取决于同名C函数的精度,但是无论如何,这是用于基准化Python或计时算法的函数。

在Windows上,此函数将基于Win32函数QueryPerformanceCounter()返回自第一次调用此函数以来经过的时间(以秒为单位)的浮点数。分辨率通常优于一微秒。

此外,还有用于对代码段进行基准测试的timeit模块。

As of 3.3, time.clock() is deprecated, and it’s suggested to use time.process_time() or time.perf_counter() instead.

Previously in 2.7, according to the 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.

Additionally, there is the timeit module for benchmarking code snippets.


回答 1

简短的答案是:大多数时候time.clock()会更好。但是,如果您要定时一些硬件(例如,您将某些算法放入GPU中),time.clock()则将摆脱这一时间,这time.time()是剩下的唯一解决方案。

注意:无论使用哪种方法,计时都将取决于您无法控制的因素(流程何时切换,多久……),这种情况会更糟,time.time()但也存在time.clock(),因此您永远不应只运行一次计时测试,但始终进行一系列测试,并查看时间的均值/方差。

The short answer is: most of the time time.clock() will be better. However, if you’re timing some hardware (for example some algorithm you put in the GPU), then time.clock() will get rid of this time and time.time() is the only solution left.

Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, …), this is worse with time.time() but exists also with time.clock(), so you should never run one timing test only, but always run a series of test and look at mean/variance of the times.


回答 2

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

但是,如果出于基准测试/性能分析的目的而安排执行代码块的时间,则应查看timeit模块

Others have answered re: time.time() vs. time.clock().

However, if you’re timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the timeit module.


回答 3

要记住的一件事:更改系统时间会影响time.time()但不会影响time.clock()

我需要控制一些自动测试的执行。如果测试用例的一个步骤花费的时间超过给定的时间,则该TC将被中止以继续下一个步骤。

但有时需要更改系统时间(以检查被测应用程序的调度程序模块),因此在将来设置系统时间几小时后,TC超时到期并且测试用例被中止。我不得不从切换time.time()time.clock()正确处理此问题。

One thing to keep in mind: Changing the system time affects time.time() but not time.clock().

I needed to control some automatic tests executions. If one step of the test case took more than a given amount of time, that TC was aborted to go on with the next one.

But sometimes a step needed to change the system time (to check the scheduler module of the application under test), so after setting the system time a few hours in the future, the TC timeout expired and the test case was aborted. I had to switch from time.time() to time.clock() to handle this properly.


回答 4

clock() ->浮点数

返回自进程开始或首次调用以来的CPU时间或实时时间clock()。这与系统记录一样精确。

time() ->浮点数

以秒为单位返回当前时间。如果系统时钟提供了小数秒,则可能会出现。

通常time()更精确,因为操作系统不会以存储系统时间(即实际时间)的精度来存储进程运行时间

clock() -> floating point number

Return the CPU time or real time since the start of the process or since the first call to clock(). This has as much precision as the system records.

time() -> floating point number

Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.

Usually time() is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)


回答 5

取决于您所关心的。如果您指的是WALL TIME(例如,墙上的时钟上的时间),则time.clock()无法提供准确性,因为它可以管理CPU时间。

Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provides NO accuracy because it may manage CPU time.


回答 6

time()具有比clock()Linux 更好的精度。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

using clock():

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

time() has better precision than clock() on Linux. clock() only has precision less than 10 ms. While time() gives prefect precision. My test is on 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

using clock():

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

回答 7

区别是特定于平台的。

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

对于您描述的示例种类,您可能需要“ timeit”模块。

The difference is very platform-specific.

clock() is very different on Windows than on Linux, for example.

For the sort of examples you describe, you probably want the “timeit” module instead.


回答 8

正如其他人指出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)

time.clock_settime_ns(clock_id, time:int)

time.monotonic_ns()

time.perf_counter_ns()

time.process_time_ns()

time.time_ns()

这些函数类似于不带_ns后缀的版本,但是作为Python int返回几纳秒。

正如其他人也指出的那样,使用该timeit模块来计时功能和小的代码片段。

As others have noted time.clock() is deprecated in favour of time.perf_counter() or time.process_time(), but Python 3.7 introduces nanosecond resolution timing with time.perf_counter_ns(), time.process_time_ns(), and time.time_ns(), along with 3 other functions.

These 6 new nansecond resolution functions are detailed in PEP 564:

time.clock_gettime_ns(clock_id)

time.clock_settime_ns(clock_id, time:int)

time.monotonic_ns()

time.perf_counter_ns()

time.process_time_ns()

time.time_ns()

These functions are similar to the version without the _ns suffix, but return a number of nanoseconds as a Python int.

As others have also noted, use the timeit module to time functions and small code snippets.


回答 9

在Unix上,time.clock()测量当前进程已使用的CPU时间量,因此,它对于测量过去某个时间点的经过时间没有好处。在Windows上,它将测量自第一次调用该功能以来经过的时钟秒数。在任何一个系统上,time.time()将返回自纪元以来经过的秒数。

如果您正在编写仅适用于Windows的代码,则两者都可以使用(尽管您将以不同的方式使用两者-time.clock()不需要减法)。如果这将要在Unix系统上运行,或者您想要保证可移植的代码,则需要使用time.time()。

On Unix time.clock() measures the amount of CPU time that has been used by the current process, so it’s no good for measuring elapsed time from some point in the past. On Windows it will measure wall-clock seconds elapsed since the first call to the function. On either system time.time() will return seconds passed since the epoch.

If you’re writing code that’s meant only for Windows, either will work (though you’ll use the two differently – no subtraction is necessary for time.clock()). If this is going to run on a Unix system or you want code that is guaranteed to be portable, you will want to use time.time().


回答 10

简短的答案:使用time.clock()在Python中计时。

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

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

Short answer: use time.clock() for timing in Python.

On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number.

time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value.


回答 11

据我所知,time.clock()具有您的系统所允许的精度。

To the best of my understanding, time.clock() has as much precision as your system will allow it.


回答 12

我使用这段代码比较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

时钟()= 0.0993572257367

I use this code to compare 2 methods .My OS is windows 8 , processor core 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

output:

time() = 0.0993799996376

clock() = 0.0993572257367


回答 13

正确答案:它们都是分数的相同长度。

但其速度更快,如果subjecttime

一些测试用例

import timeit
import time

clock_list = []
time_list = []

test1 = """
def test(v=time.clock()):
    s = time.clock() - v
"""

test2 = """
def test(v=time.time()):
    s = time.time() - v
"""
def test_it(Range) :
    for i in range(Range) :
        clk = timeit.timeit(test1, number=10000)
        clock_list.append(clk)
        tml = timeit.timeit(test2, number=10000)
        time_list.append(tml)

test_it(100)

print "Clock Min: %f Max: %f Average: %f" %(min(clock_list), max(clock_list), sum(clock_list)/float(len(clock_list)))
print "Time  Min: %f Max: %f Average: %f" %(min(time_list), max(time_list), sum(time_list)/float(len(time_list)))

我不是在瑞士的实验室工作,但已经过测试。

基于这样一个问题:time.clock()是不是更好time.time()

编辑:time.clock()是内部计数器,因此max 32BIT FLOAT如果不存储第一个/最后一个值,则不能在外部使用,受到限制,不能继续计数。无法合并另一个计数器…

Right answer : They’re both the same length of a fraction.

But which faster if subject is time ?

A little test case :

import timeit
import time

clock_list = []
time_list = []

test1 = """
def test(v=time.clock()):
    s = time.clock() - v
"""

test2 = """
def test(v=time.time()):
    s = time.time() - v
"""
def test_it(Range) :
    for i in range(Range) :
        clk = timeit.timeit(test1, number=10000)
        clock_list.append(clk)
        tml = timeit.timeit(test2, number=10000)
        time_list.append(tml)

test_it(100)

print "Clock Min: %f Max: %f Average: %f" %(min(clock_list), max(clock_list), sum(clock_list)/float(len(clock_list)))
print "Time  Min: %f Max: %f Average: %f" %(min(time_list), max(time_list), sum(time_list)/float(len(time_list)))

I am not work an Swiss labs but I’ve tested..

Based of this question : time.clock() is better than time.time()

Edit : time.clock() is internal counter so can’t use outside, got limitations max 32BIT FLOAT, can’t continued counting if not store first/last values. Can’t merge another one counter…


回答 14

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

  • Unix上,以秒为单位返回当前处理器时间,以浮点数表示。
  • Windows上,此函数返回自第一次调用此函数以来经过的挂钟秒数,作为浮点数

    print(time.clock()); time.sleep(10); print(time.clock())
    # Linux  :  0.0382  0.0384   # see Processor Time
    # Windows: 26.1224 36.1566   # see Wall-Clock Time

那么选择哪个功能呢?

  • 处理器时间:这是该特定进程在CPU上主动执行所花费的时间。睡眠,等待Web请求或仅执行其他进程的时间不会对此有所帮助。

    • 采用 time.process_time()
  • 墙上时钟时间:这指的是“挂在墙上的时钟上”经过了多少时间,即不是实时时间。

    • 采用 time.perf_counter()

      • time.time() 还可以测量挂钟时间,但可以重置,因此您可以返回到过去
      • time.monotonic() 无法重置(单调=仅前进),但精度低于 time.perf_counter()

time.clock() was removed in Python 3.8 because it had platform-dependent behavior:

  • On Unix, return the current processor time as a floating point number expressed in seconds.
  • On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number

    print(time.clock()); time.sleep(10); print(time.clock())
    # Linux  :  0.0382  0.0384   # see Processor Time
    # Windows: 26.1224 36.1566   # see Wall-Clock Time
    

So which function to pick instead?

  • 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()

回答 15

比较Ubuntu Linux和Windows 7的测试结果。

在Ubuntu上

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5005500316619873

在Windows 7上

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5

Comparing test result between Ubuntu Linux and Windows 7.

On Ubuntu

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5005500316619873

On Windows 7

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5