0

I know the execution time for any python program shall depend on the OS and cannot be controlled by the User. But what I want is the program to go in sleep if the execution time is lower than necessary.

Let's say I have a python program which has a print statement at the end.

def foo():
    ...
    ...
    return(ans)

print(foo())

Using timeit I have evaluated the range of execution time taken for foo. Let it be from 0.8 seconds to 5.5 seconds. I choose the execution time of the complete script as 10 seconds to be on the safe side.

I want the program to add delay of 9.2 seconds before print statement if the execution of foo was completed in 0.8 seconds. Likewise a delay of 4.5 seconds if execution was completed in 5.5 seconds.

pani3610
  • 83
  • 1
  • 4

2 Answers2

1

You basically just have to sleep for the amount of time that is the difference between the maximum time and actual execution time. you could also make a general purpose decorator.

class padtime:
    def __init__(self, maxtime):
        self.maxtime = float(maxtime)

    def __call__(self, f):
        def _f(*args, **kwargs):
            start = time.time()
            ret = f(*args, **kwargs)
            end = time.time()
            delay = self.maxtime - (end - start)
            if delay > 0.0:
                time.sleep(delay)
            return ret
        return _f

@padtime(9.5)
def foo():
    ...
    return("Answer")

that could be applied to any function.

Keith
  • 42,110
  • 11
  • 57
  • 76
0

You can measure the execution time of foo() using two calls to time.time(). You can then compute the amount of time to stall the execution of the program using the computed execution time of foo():

import time

def foo():
    ...

start_time = time.time()
foo()
end_time = time.time()
if end_time - start_time < 10:
    time.sleep(10 - (end_time - start_time))

Note that we use time.sleep() rather than a while loop that repeatedly checks whether enough time has elapsed, since busy waiting wastes resources.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • Kinda silly to bring up "wasting resources" when time is a resource and OP wants to intentionally waste it but ¯\\_(ツ)_/¯ – ddejohn Mar 19 '22 at 05:14
  • works well within the resolution required. Thanks! @BrokenBenchmark – pani3610 Mar 19 '22 at 05:25
  • @ddejohn Yeah, but busy waiting is a general pattern one should avoid. I was going to comment that on your answer, but it was deleted before I could answer. (I wasn't the one who downvoted, for the record.) – BrokenBenchmark Mar 19 '22 at 05:26
  • 1
    @ddejohn However, time is a different resource from CPU cycles. A sleep allows another process to use those cycles. – Keith Mar 19 '22 at 05:29