Reputation: 25
I thought I'd sign up to help me learn more coding with Python. I recently signed up to code academy and have been doing the online Python course which has helped a lot.
I've decided to give myself a small project to continue learning but have ran into a problem (searched on here and still no help.)
I'm wanting to write a small function of code for a midi step sequencer, for simplicity I'm omitting midi for now and looking at it in the most logical way I can.
What I want to do is:
The trouble I have is I can't find any possible way to iterate through a list in the time domain. I have looked at the time.sleep
function but read this is not accurate enough. Is there another method. I don't want to use any libraries.
Any pointers would be a huge help as I'm struggling to find any available resources for running through a loop at a specified amount of time between each value in the loop.
Upvotes: 1
Views: 160
Reputation: 521
The reason time.sleep
might not be accurate for you might be due to the way you are using it. Try this:
import time
sleeptime = 0.0208333 #in seconds
for your_loop_here:
start = time.time()
#do stuff here
time.sleep(max(sleeptime - (time.time() - start), 0))
I have used this method to limit frame rate in computer vision processing. All it does is account the loop iteration time in the sleep so that the time for each loop is as accurate as possible. It might work for you too. Hope this helps!
Well of course there's a much more accurate way to do this, which would be to write all your code in assembly and finely adjust the clock speed of your CPU so that each iteration takes a fixed amount of time, but this might be too impractical for your use case.
Upvotes: 1
Reputation: 384
Could you say why sleep is not accurate enough?
If you wish so, you can keep track of the elapsed time yourself using something like time.thread_time_ns
so:
def sleep(pause_time):
initial_time = time.thread_time_ns()
while( time.thread_time_ns() - initial_time < pause_time):
pass
So this is your own sleep function
Upvotes: 2