Is it possible to receive the output of time.time() in Python 2.5 as a Decimal?
If not (and it has to be a float), then is it possible to guarantee that inaccuracy will always be more than (rather than less than) the original value. In other words:
>>> repr(0.1)
'0.10000000000000001' # More than 0.1 which is what I want
>>> repr(0.99)
'0.98999999999999999' # Less than 0.99 which is unacceptable
Code example:
import math, time
sleep_time = 0.1
while True:
time_before = time.time()
time.sleep(sleep_time)
time_after = time.time()
time_taken = time_after - time_before
assert time_taken >= sleep_time, '%r < %r' % (time_taken, sleep_time)
EDIT:
Now using the following (which does not fail in testing but could still theoretically fail):
import time
from decimal import Decimal
def to_dec(float_num):
return Decimal('%2f' % float_num)
sleep_time = to_dec(0.1)
while True:
time_before = to_dec(time.time())
time.sleep(float(sleep_time))
time_after = to_dec(time.time())
time_taken = time_after - time_before
assert time_taken >= sleep_time, '%r < %r' % (time_taken, sleep_time)
print 'time_taken (%s) >= sleep_time (%s)' % (time_taken, sleep_time)
You could simply multiple
time.time()by some value to get the precision you want (note that many calls can’t guarantee sub-second accuracy anyways). So,Will satisfy your condition that
endTime - startTime >= sleepTime