Python's time.clock() vs. time.time() accuracy?

后端 未结 16 1434
忘掉有多难
忘掉有多难 2020-11-22 08:22

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          


        
相关标签:
16条回答
  • 2020-11-22 09:06

    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
    
    0 讨论(0)
  • 2020-11-22 09:08

    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.

    0 讨论(0)
  • 2020-11-22 09:10

    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.

    0 讨论(0)
  • 2020-11-22 09:11

    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.

    0 讨论(0)
提交回复
热议问题