3
start = time.clock()
print("test ")
time.sleep(1)
print(time.clock()-start)

The final line prints the result normally but sometimes it gives a result less than 1 (0.9962501944182808 or 0.9886929485969909 etc.)

If I have made the code sleep for 1 second with time.sleep(1) I would have thought that the result would always greater than 1.

It is not precise so how can I calculate time consumed by my code with built-in modules?

Gahan
  • 4,075
  • 4
  • 24
  • 44
  • 4
    time.sleep() is not that precise (and it cannot be on any non-RT OS anyway). As the [`time.sleep()`](https://docs.python.org/3/library/time.html#time.sleep) documentation states: `The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.` – zwer Jun 10 '17 at 17:39
  • Related: https://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep especially this answer: https://stackoverflow.com/a/1133879/6622817 – Taku Jun 10 '17 at 17:42
  • I'm guessing this is Windows? (Microsoft's implementation [favors slightly shorter sleeps](https://stackoverflow.com/a/15967564/14122)). – Charles Duffy Jun 10 '17 at 17:48

1 Answers1

2

From the documentation

The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

Also, you can read this answer about the sleep function's accuracy.

Isdj
  • 1,835
  • 1
  • 18
  • 36