Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
Pushpak Dagade Avatar asked Dec 17 '25 16:12

Pushpak Dagade


1 Answers

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]()
like image 175
Gabi Purcaru Avatar answered Dec 19 '25 06:12

Gabi Purcaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!