Skip to content Skip to sidebar Skip to footer

Time.clock() Doesn't Return Time Properly

This code: import time now = time.clock() while now + 5 > time.clock(): print time.clock() time.sleep(1) print 'Woke up' returns: 0.015718 Woke up 0.015814 Woke up

Solution 1:

You probably should read the manual:

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. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

That is assuming you're using UNIX (fx Linux or iOS) the behaviour is correct. time.clock returns the amount of CPU time the process has consumed, when sleeping you don't consume any CPU time.

Of course the difference between UNIX and Windows makes this function useless unless you detect which behavior is in effect and act accordingly.

Solution 2:

Based on the pattern this might do the trick. time.clock() will give you the processing time and time.time() - now_time() will give how many seconds has passed through each time.sleep(1)

import time
now = time.clock()
now_time = time.time()
while now + 5 > time.clock():
    printtime.time() - now_time + time.clock()
    time.sleep(1)
    print"Woke up"

Post a Comment for "Time.clock() Doesn't Return Time Properly"