Metalshark
Metalshark

Reputation: 8482

Python 2.5 time.time() as decimal

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)

Upvotes: 0

Views: 4755

Answers (3)

Alex Smith
Alex Smith

Reputation: 1535

You could format your float value as so:

>>> '%.2f' % 0.99
'0.99'

See Python's String Formatting Operations

Upvotes: 1

NPE
NPE

Reputation: 500873

It is for a timing function which needs to register a time before and after a call that may sleep. So time after - time before >= sleep time, which is not always the case with floats.

I think your requirements are inconsistent. You seem to want to call the same function twice, and have the first call round the result downwards, and the second call to round the result upwards.

If I were you:

  1. I'd time many calls instead of just one.
  2. When drawing any conclusions I'd take into account the resolution of the timer and any floating-point issues (if relevant).

Upvotes: 0

brc
brc

Reputation: 5391

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,

startTime = int(time.time() * 100)
#...
endTime = int(time.time() * 100)

Will satisfy your condition that endTime - startTime >= sleepTime

Upvotes: 3

Related Questions