How do I ensure that a Python while-loop takes a particular amount of time to run?

后端 未结 3 1408
南旧
南旧 2021-01-01 03:37

I\'m reading serial data with a while loop. However, I have no control over the sample rate.

The code itself seems to take 0.2s to run, so I know I won\'t be able to

3条回答
  •  情话喂你
    2021-01-01 04:02

    Just measure the time running your code takes every iteration of the loop, and sleep accordingly:

    import time
    
    while True:
        now = time.time()            # get the time
        do_something()               # do your stuff
        elapsed = time.time() - now  # how long was it running?
        time.sleep(1.-elapsed)       # sleep accordingly so the full iteration takes 1 second
    

    Of course not 100% perfect (maybe off one millisecond or another from time to time), but I guess it's good enough.


    Another nice approach is using twisted's LoopingCall:

    from twisted.internet import task
    from twisted.internet import reactor
    
    def do_something():
        pass # do your work here
    
    task.LoopingCall(do_something).start(1.0)
    reactor.run()
    

提交回复
热议问题