Get decimal part of floating point number in python
I want my Python2 daemon to wake up and do something exactly on the second.
Is there a better way to get the abbreviated part of a floating point number for a different sleep time:
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.
Sleep time will vary depending on how much work was done in that second.
Is there a Sleep Before feature that I am not aware of? 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.
Thank. Mark.
source to share
Use math.modf()
math.modf(x)
Returns the fractional and integer parts of x. Both results are x-sign and are floats.
Example:
>>> from math import modf
>>> modf(3.1234)
(0.12340000000000018, 3.0)
source to share
time.sleep
not guaranteed to wake up exactly when you say so, it may be somewhat inaccurate.
To get the part after the decimal place, use the modulus operator ( %
):
>>> 3.5 % 1
.5
eg:.
>>> t = time.time()
>>> t
1430963764.102048
>>> 1 - t % 1
0.8979520797729492
As for the "sleep til", you might be interested in the scheduling module which is built around this idea: https://docs.python.org/2/library/sched
source to share