Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there differences in Python time.time() and time.clock() on Mac OS X?

Tags:

python

time

macos

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?

like image 222
wwwilliam Avatar asked Dec 08 '22 14:12

wwwilliam


2 Answers

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

like image 157
TerryA Avatar answered Dec 11 '22 08:12

TerryA


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
like image 42
unutbu Avatar answered Dec 11 '22 09:12

unutbu