Skip to content Skip to sidebar Skip to footer

Why Are There Differences In Python Time.time() And Time.clock() On Mac Os X?

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

Solution 1:

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

Solution 2:

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.clockelse:
    # On most other platforms the best timer is time.time()
    default_timer = time.time

Solution 3:

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?

Post a Comment for "Why Are There Differences In Python Time.time() And Time.clock() On Mac Os X?"