-1
idx = 0

start_time = time.time()

while True:
    idx += 1
    time.sleep(0.01)
    if  idx > 100:
        break


print(time.time() - start_time)

Normally, This code have to take 1 second (100 * 0.01) to run. But if I run, it takes about 1.57 seconds. So, I want to more correct timer with millisecond unit. Please help me.

UP Manager
  • 63
  • 1
  • 9
  • [How accurate is python's time.sleep()?](https://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep) – Guy Jun 27 '22 at 04:48
  • I just understand, So there haven't any solution to run code every millisecond unit? about 8~10 milliseconds on window/mac pc. I tried with QThread and timer, but had same problem. – UP Manager Jun 27 '22 at 12:24

1 Answers1

2

If you want to wait for a second, use time.sleep(1). There is overhead in each "sleep" call, and overhead in the Python code you're executing, all of which you're counting. Also, a sleep call on all the major operating systems is merely guaranteed to sleep for AT LEAST the time you specify. These are not real-time systems.

If time.sleep(1) does not work, then I suggest you use something like this instead:

before = time.time()
while time.time() - before < 1.0:
    time.sleep( 0.1 )
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • `pass` will give better results than `sleep` – Guy Jun 27 '22 at 04:42
  • @Guy -- It absolutely will NOT! `pass` will consume 100% of a CPU, sucking out performance and using more power. ALWAYS use some form of `sleep` in a tight loop like this. – Tim Roberts Jun 27 '22 at 06:43
  • The OP asked for a more accurate timer. This will give more accurate results (closer to 1 second) than what he has, but it still has the inaccuracy issues of using `sleep()`. – Guy Jun 27 '22 at 06:55
  • If I do ```time.sleep(0.0000001)```, it's take about 0.015 second actually. So I can know ```sleep``` take about 0.015 second as default even no take time. So I hope to solution for that, QThread and timer also have same problem. – UP Manager Jun 27 '22 at 12:19
  • Again, these are not real-time systems. There is no hardware interrupt for when your timer expires. When the system's timer tick goes off (every 16ms or 10ms, depending on OS), the scheduler runs through the list of threads that are waiting for timers. If any of them have expired, those threads are made "ready to run". The scheduler then picks one of the "ready to run" threads to slot into a CPU. It might be yours, it might not. If you're making a medical device that needs millisecond timing, you need timer hardware and a driver. – Tim Roberts Jun 27 '22 at 16:29