12

I would like my Python2 daemon to wake up and do something exactly on the second.

Is there a better way to get the decmal part of a floating point number for a sleep time other then:

now = time.time()               #get the current time in a floating point format
left_part = long(now)           #isolate out the integer part
right_part = now - left_part    #now get the decimal part
time.sleep(1 - right_part)      #and sleep for the remaining portion of this second.

The sleep time will be variable depending on how much work was done in this second.

Is there a "Sleep till" function I don't know about? or, is there a better way to handle this?

I would like my daemon to be as efficient as possible so as not to monopolize too much CPU from other processes.

Thanks. Mark.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
Cool Javelin
  • 776
  • 2
  • 10
  • 26

3 Answers3

17

time.sleep isn't guaranteed to wake up exactly when you tell it to, it can be somewhat inaccurate.

For getting the part after the decimal place, use the modulus (%) operator:

>>> 3.5 % 1
.5

e.g.:

>>> t = time.time()
>>> t
1430963764.102048
>>> 1 - t % 1
0.8979520797729492

As for "sleep til", you might be interested in the sched module, which is built around that idea: https://docs.python.org/2/library/sched

Devin Jeanpierre
  • 92,913
  • 4
  • 55
  • 79
  • 1
    Thanks Devin. I think this is perfect. I guess when I said "exactly" I really meant "as close as possible". My real code line is now time.sleep(1 - time.time() %1). I love it. – Cool Javelin May 07 '15 at 23:54
  • Note, this goes funny if the number is negative. `-3.7 % 1` is 0.3, not 0.7. – Schwern Dec 21 '22 at 00:10
13

Use math.modf()

math.modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

Example:

>>> from math import modf
>>> modf(3.1234)
(0.12340000000000018, 3.0)
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • That’s some serious roundoff error, caused by internal binary conversion. That little discrepancy could be a problem in some cases, especially if you’ looking to comparing with other values. – Manngo Apr 15 '22 at 04:05
0
n=(float(input('Enter the Decimal Value: ')))
n1=(str(n))
l=0
s=''
for c in n1:
    if c=='.' or l==1:
        l=1
        if c!='.':
            s+=c#storing the decimal part
# Converting the decimal part to the integer part
print('0.{0}'.format(int(s)))

in this process you'll get the absolute number of digits and acurate value of the floating values in python.

Jim
  • 83
  • 8
Tuhin Mitra
  • 555
  • 7
  • 19