If you know the code you want to run will take less than 1 second, then 1 - elapsed time
will give you the remaining time to sleep, no while
loop required.
now = time.time()
foo()
time.sleep(1 - (time.time() - now))
There will be some overhead with the arithmetic, but it's within 1/100 of a second and will be strictly greater than 1 second, as you request. I ran the following code:
import time
import random
def foo():
time.sleep(random.random())
now = time.time()
foo()
time.sleep(1 - (time.time() - now))
print "Time elapsed: {}".format(time.time() - now)
Output:
Time elapsed: 1.00379300117
You can run this several times to verify it gives the output you want, no matter how long foo
takes.
Unless it takes longer than 1 second, then the sleep time will be negative which will result in IOError
. You would need to check for that case.
Or, if you need to kill the function if 1 second has passed, check this question