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

后端 未结 3 1417
南旧
南旧 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:08

    An rather elegant method is you're working on UNIX : use the signal library

    The code :

    import signal
    
    
    def _handle_timeout():
        print "timeout hit" # Do nothing here
    
    def second(count):
        signal.signal(signal.SIGALRM, _handle_timeout)
        signal.alarm(1)
        try:
            count += 1 # put your function here
            signal.pause()
    
        finally:
            signal.alarm(0)
            return count
    
    
    if __name__ == '__main__':
    
        count = 0
        count = second(count)
        count = second(count)
        count = second(count)
        count = second(count)
        count = second(count)
    
        print count
    

    And the timing :

     georgesl@cleese:~/Bureau$ time python timer.py
     5
    
     real   0m5.081s
     user   0m0.068s
     sys    0m0.004s
    

    Two caveats though : it only works on *nix, and it is not multithread-safe.

提交回复
热议问题