4

I'm running Mac OS X 10.8 and get strange behavior for time.clock(), which some online sources say I should prefer over time.time() for timing my code. For example:

import time    
t0clock = time.clock()
t0time = time.time()
time.sleep(5)
t1clock = time.clock()
t1time = time.time()
print t1clock - t0clock
print t1time - t0time

0.00330099999999 <-- from time.clock(), clearly incorrect
5.00392889977    <-- from time.time(), correct

Why is this happening? Should I just use time.time() for reliable estimates?

wwwilliam
  • 9,142
  • 8
  • 30
  • 33

3 Answers3

7

From the docs on 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.

From the docs on time.time:

Return the time in seconds since the epoch as a floating point number. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

time.time() measures in seconds, time.clock() measures the amount of CPU time that has been used by the current process. But on windows, this is different as clock() also measures seconds.

Here's a similar question

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • it helps to understand that some parts of python (particularly the date/time functions) are just very thin wrappers around "traditional" calls that exist in the operating system. and these vary from platform to platform... – andrew cooke Jul 06 '13 at 00:08
7

Instead of using time.time or time.clock use timeit.default_timer. This will return time.clock when sys.platform == "win32" and time.time for all other platforms.

That way, your code will use the best choice of timer, independent of platform.


From timeit.py:

if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

time.time() returns the "wall clock" time.

time.clock() returns the time used by the processor, if you call time.sleep() you are not using the processor, the process is just unscheduled until the timer decides to give the process the cpu back (except on windows where it returns the "wall clock" time).

see this question: time.h clock() broken on OS X?

Community
  • 1
  • 1
dnozay
  • 23,846
  • 6
  • 82
  • 104