Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to sleep milliseconds time.sleep(0.001) not working as expected, alternatives?

I’m trying to run a function approximately 200 times a second (give or take +- 50). When using time.sleep(0.005), I find that it sleeps for much longer. I understand that time.sleep is not accurate, but my use case doesn’t need much accuracy either.

I searched this problem up and it seems to be an issue with Windows 10 & 11 in particular: https://bugs.python.org/issue44681

They don’t seem to be keen on fixing this issue, so I was wondering what alternatives are there for sleeping for around a millisecond?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tested this code:

last_time = time.time()
counter = 0
while True:
    now = time.time()
    if now - last_time >= 1:
        print(counter)
        last_time = now
        counter = 0
    counter += 1

Which gave me around 64 to 65 on my computer and around 70 on my laptop.

>Solution :

While time.sleep() can be useful for some purposes, it is not the most accurate or reliable way to achieve precise timing in a program.

One alternative you could consider is using the perf_counter() function from the time module instead of sleep(). The perf_counter() function returns a high-resolution performance counter value, which can be more accurate than sleep() for measuring elapsed time.

Here is an example of how you could use perf_counter() to achieve a target frequency of approximately 200 times per second:

import time

target_frequency = 200  # Hz
target_period = 1 / target_frequency  # seconds

last_time = time.perf_counter()
counter = 0
while True:
    now = time.perf_counter()
    elapsed_time = now - last_time
    if elapsed_time >= target_period:
        print(counter)
        last_time = now
        counter = 0
    counter += 1
    # Sleep for a short amount of time to allow other processes to run
    time.sleep(0.001)

By using perf_counter() to measure the elapsed time and sleeping for a short period of time after each iteration of the loop, you should be able to achieve a frequency that is close to the target frequency of 200 times per second.

You may also want to consider using a separate thread or process to run your program, as this can help to improve the accuracy of the timing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading