1

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
0.015942
Woke up
0.016107
Woke up
0.01625
Woke up
0.016363

As you can see, the time returned does not seem to return the elapsed time with seconds represented as integers, even though that is what the documentation says it should do. What is wrong here?

EDIT: I'm on Mac OS X El Capitan

Sahand
  • 7,980
  • 23
  • 69
  • 137
  • https://docs.python.org/3/library/time.html#time.clock – user3159253 May 09 '16 at 09:09
  • Citing the doc: 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. – user3159253 May 09 '16 at 09:10
  • What OS are you working on? – Neo May 09 '16 at 09:11
  • See my edit. Regarding the doc, it still says it should be expressed in seconds, which is not the case here. – Sahand May 09 '16 at 09:13
  • The documentation states tha it returns a float, not an integer: "...as a floating point number...". It is being expressed in seconds, it's CPU usage time, not CPU elapsed time, The sleep() function does not use CPU time. You are probably looking for time.time() which returns elapsed time. – João Pinto May 09 '16 at 09:38
  • related: [Measure time elapsed in Python?](http://stackoverflow.com/q/7370801/4279) – jfs May 10 '16 at 13:57

2 Answers2

2

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.

skyking
  • 13,817
  • 1
  • 35
  • 57
1

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():
    print time.time() - now_time + time.clock()
    time.sleep(1)
    print "Woke up"
KitoKunX
  • 21
  • 4