Frank Vel
Frank Vel

Reputation: 1208

Make a timer using sleep in python. How to account for computation time?

I'm trying to make a simple timer which prints the time remaining every second.

for k in range(100):
    print(100-k)
    t.sleep(1)
#output
#100
#99
#98
#...
#1

However, this will take slightly longer than 100 seconds, because there will be a delay added when print() is used. For long periods, this is slightly noticeable. Is there a way to account for this, and accurately display the time every second? I know I could just sleep(100), but this wouldn't let the time left be printed.

Upvotes: 2

Views: 520

Answers (3)

Taku
Taku

Reputation: 33714

Using time.sleep will never give you the accurate time for your timer, since the time it takes is the one second sleep time + printing time, you can use threading.Timer to get more accurate results. https://repl.it/Hwkt :

import threading, time

start_time=time.time()
def count_loop(counter):
  if counter <= 0: 
    print("it took  "+str(float(time.time()-start_time)*1000)+" Milliseconds")
    return

  threading.Timer(1.0, count_loop, args=[counter-1]).start()
  print(counter)      

count_loop(100)

This is still not accurate, but with only very minimum offset, only 45 ms. However, when using time.sleep from legendisback's example, there is apparently 81 ms delay. https://repl.it/HwlK

Upvotes: 1

xjcl
xjcl

Reputation: 15309

You can use time.time() to measure elapsed time.

import time
start_time = time.time()

for k in range(100):
    # k seconds SHOULD be elapsed at this point
    print(100 - k)
    slept_time = time.time() - start_time
    time.sleep(1 + k-slept_time)

Upvotes: 1

legend-is-back
legend-is-back

Reputation: 443

import time
start_time=time.time()
for k in range(25):
    print(25-k)
    time.sleep(1)
print("it took  "+str(float(time.time()-start_time)*1000)+" Milliseconds")

the output with print is: it took 26412.75382041931 Milliseconds

the output without print : it took 25053.035020828247 Milliseconds

it should have been just 25000 milliseconds but it is not

printing will take time, even reading the code takes time point is don't expect accurate timing with time.sleep() !!!

Upvotes: 1

Related Questions