开发者

python timed execution of code

I want to execute a piece of my code in exactly the same time every 开发者_运维知识库time I execute it, somewhat like playing a media file... (the same piece of code is executed in exactly the same amount of time every time)

Is this possible in python?


This should do the trick:

def run_with_delay(funcs, interval):
    for f in funcs[:-1]:
        before = time()
        f()
        # compensate the interval with the execution time.
        # NB: careful for functions that have a greater
        #     execution time than interval
        after = time()
        if after - before < interval:
            sleep(interval - (after - before))
    # last function is taken separately because we don't need
    # an extra useless sleep
    funcs[-1]()


I don't think this can be guaranteed by a language construct (in any language) -- you'd have to be on a real-time operating system. I believe multimedia applications take advantage of device-level buffering to compensate for timing jitter in the OS process scheduler.


I should think this would be impossible in an operating system which interleaves instructions to simulate simultaneous execution of multiple threads.

You would need a real-time library or language in order to stipulate deadlines for your code, and even then execution cannot be guaranteed in the allotted time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜