user3246167 user3246167 - 1 year ago 67
Python Question

Python: how to extend execution time of code to 1 second

I'm writing a countdown clock in python, but it looks like the time module only goes down to the second. Is there a way for me to accurately determine when exactly 1 second has passed?

Seems like my question was a little confusing, let me clarify. I need to run some code, then, at the end, the program enters a while loop and exits once at least 1000 milliseconds have passed since the time the code started running

Answer Source

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()
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():

now = time.time()
time.sleep(1 - (time.time() - now))

print "Time elapsed: {}".format(time.time() - now)


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download