0

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

jayelm
  • 7,236
  • 5
  • 43
  • 61
user3246167
  • 129
  • 1
  • 15

3 Answers3

1

Here is a way which will work, though im not sure which modules you are limited to.

import time

def procedure:
    time.sleep(2.5)

# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"

2.50023603439 seconds wall time

where procedure is a reference to the function you are timing.

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129
1

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

Community
  • 1
  • 1
jayelm
  • 7,236
  • 5
  • 43
  • 61
-1

By default the time module gives you the time to the 10^-5 second

import time
time.time()
>>> 1480643510.89443
ted
  • 13,596
  • 9
  • 65
  • 107