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

I run Mac OS X 10.8 and get weird behavior for time.clock (), which, as some online sources report, I prefer over time. For instance:

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?

+4
source share
3 answers

From the docs on time.clock :

On Unix, return the current processor time as a floating point number expressed in seconds. The accuracy and, in fact, the very definition of "processor time" depends on the C function with the same name, but in any case it is a function used to benchmark Python algorithms or timekeeping.

In time.time :

Returns the time in seconds since an era as a floating point number. Please note: although time is always returned as a floating point number, not all systems provide time with better accuracy than 1 second. Although this function usually returns non-decreasing values, it can return a lower value than the previous call if the system clock was set between two calls.

time.time() measures in seconds, time.clock() measures the amount of processor time that was used by the current process. But in windows, this is different from how clock() also measures seconds.

Here is a similar question

+7
source

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.

This way, your code will use the best timer choice, regardless 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 
+7
source

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 simply unplanned until the timer decides to return the process back (with the exception of windows where it returns "wall-mounted" time hours ").

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

0
source

Source: https://habr.com/ru/post/1489996/


All Articles