An accurate python sleep function

2024/9/20 15:31:11

I've tried time.sleep(), but its accuracy is total garbage. Consider this loop, for instance:

for i in range(10000000):print(i)sleep(.334)

Watch the numbers it prints. If it's anything like my computer, it's not even remotely regular. Is this function supposed to be accurate? Have I found a bug somewhere in my system?

If this function is not supposed to be accurate, what function would be more accurate?

Answer

If you're just looking at the output, buffering might make it appear slightly jittery. You could try to explicitly flush the output, but then you're also at the mercy of whatever is displaying the output. I might even hazard a guess that you're using Jupyter Notebook in your browser, which will also have a bunch of buffering/latency as it updates.

Another issue is that if you expect to be running every 1/3 of a second, is that you will suffer from accumulated errors. It will take a little time to run the loop, print a value (printing will take orders of magnitude more time than the other parts), then start to sleep again. A way to bypass this would be that after you finish doing whatever you want to do (I assume something more interesting than count), compute the time until the next 1/3rd of a second and sleep for that amount of time. Something like:

import random
import timesleep_until = time.monotonic() + 1/3for n in range(100):print(time.monotonic() % 100, n)time.sleep(random.random() / 4) # some "work"now = time.monotonic()if sleep_until > now:time.sleep(sleep_until - now)else:pass#print('task took too long')sleep_until += 1/3

For me it gives something like:

48.34696656104643 0
48.68041984003503 1
49.08346292399801 2
49.41925806296058 3
49.72542790300213 4
50.07280854298733 5
50.41882419097237 6
50.74827564903535 7
51.08352101803757 8
51.41813271504361 9
51.75208444998134 10
52.08399672002997 11
52.41870043799281 12

So it bounces around a bit (I'm also running this in Jupyter, which may contribute), but won't stack up error as it runs.

The real question though is what are you trying to do?

https://en.xdnf.cn/q/119314.html

Related Q&A

How to map python dictionary key values to each other?

Suppose we have two dictionaries as below: dict_a_to_b = {2:4, 6:9, 9:3} dict_a_to_c = {2: 0.1, 6:0.2, 9: 0.8}How to map these two dictionaries to make dict_c_to_b in python? dict_c_to_b = {0.1:4, 0.2…

Installing Keyrock on Fiware in my Virtual Machine

I want install keyrock and I follow these steps, but in the step three, when I write in the console:sudo python tools/install_venv.pyConsole shows me the next fail:Could you help me, please?

Cartopy error when attempting to plot rivers

When attempting to use Cartopy to plot rivers, Im getting a URL error. Im not even sure the rivers feature will plot what I want...Im attempting to get the Galveston Ship Channel to show on my map. Her…

Have the address of the client in python

My request is : I have my web pages created in python (wherein there is html code), each pages has a button to go to the next page. Is it possible to get the address of the client when we submit an htm…

try/except issue in Python

I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book …

Counting the number of vowels in a string using for loops in Python

Python Code:sentence = input(Enter a string:) vowel = A,a,E,e,I,i,O,o,U,u Count = 0 for vowel in sentence:Count += 1 print(There are {} vowels in the string: \{}\.format(Count,sentence))I am trying to …

Sum the values of specific rows if the rows have same values in specific column

I have a data frame like this:a b c 12456 11 123.1 12678 19 345.67 13278 19 1235.345or in another format <table><tr><td>12456</td><td>11</td><td>1…

Plotting Interpolated 3D Data As A 2D Image using Matplotlib

The data set is made of a list dfList containing pandas DataFrames, each DataFrame consisting of the column Y and an identical index column. I am trying to plot all the DataFrames as a 2D plot with pix…

Plotting a flow duration curve for a range of several timeseries in Python

Flow duration curves are a common way in hydrology (and other fields) to visualize timeseries. They allow an easy assessment of the high and low values in a timeseries and how often certain values are …

HTML variable value is not changing in Flask

I have written this code in Flaskans = 999 @app.route(/, methods=[POST, GET]) def home():flag = 0global anssession["ans"] = 0if (request.method == "POST"):jsdata = request.form[data…