A Male Huuski
A Male Huuski

Reputation: 23

How to delay a function call counting the execution time of the function itself

I'm trying to loop a specific function exactly after a specified amount of time. I pondered using time.sleep() for this, however the time module does not count the runtime of the function itself.
For example:

def function(*args, **kwargs):
   ## Some processing happens here that takes 0.9 seconds
   time.sleep(1)

This function would take 1.9 seconds to execute. However, I would like it to execute every second, including the time it took to run that function.
I don't know the exact processing time within the function; it could take 0.9, 0.92, 0.88,... seconds, so I can't simply use time.sleep(0.1).

I could time the function and substract that from the sleep time, like so:

def function(*args, **kwargs):
   start = time.time()
   ## Some processing happens here that takes 0.9 seconds
   end = time.time()
   sleep_time = 1 - (end-start)
   time.sleep(sleep_time)

However, doesn't timing the code and doing the substraction in itself take processing time, meaning that the total function takes a little more than 1 second and the schedule will be incorrect after a while?

This seems like something I could accomplish using Threading, however I've always learned that you shouldn't include threading unless you absolutely need it to speed up your runtime, and in my case it won't...

Any ideas?

Upvotes: 0

Views: 433

Answers (1)

creolo
creolo

Reputation: 338

You mean something like:

def do_work():
    print("I am working")

def work_loop():
    while True:
        do_work()
        time.sleep(1)

This way your "do_work()" function is executed every 1 seconds plus whatever it takes for your do_work() function to do its work.

Or do you want to run your function every 1 seconds, so if it takes like 0.9 seconds for do_work() to finish, you want to restart it after 0.1 seconds?

You could do that by checking the time with something like:

def do_work():
    finish_time = int(time.time()) + 1
    # do your calculations in here
    while int(time.time()) < finish_time:
        time.sleep(0.001)
    return

I would definitely suggest that you use asyncio for that kind of requirement. Otherwise your programm will just block while it is waiting.

Upvotes: 1

Related Questions