On 1/25/07, Tim Peters <tim.peters@gmail.com> wrote:
[Guido]
The only thing I would miss about this is that I am used to write certain timing loops that like to sync on whole seconds, by taking time.time() % 1.0 which nicely gives me the milliseconds in the current second. E.g.
while True: do_something_expensive_once_a_second_on_the_second() now = time.time() time.sleep(1.0 - (now % 1.0))
Indeed, the only use of floating % in the standard library I recall is the ancient
return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
from the original Wichman-Hill random() generator. Maybe we could introduce "%" as a unary prefix operator, where %x means "the fractional part of x" ;-)
Are you opposed to importing `math`? The infix spelling had important speed benefits in random.py (random() was the time-critical function in that module), but the use above couldn't care less.
time.sleep(1.0 - math.fmod(now, 1.0))
would do the same, except would be easier to reason about because it's trivially guaranteed that 0.0 <= math.fmod(x, 1.0) < 1.0 for any finite float x >= 0.0. The same may or may not be true of % (I would have to think about that, and craft a proof one way or the other -- if it is true, it would have to invoke something special about the modulus 1.0, as the inequality doesn't hold for % for some other modulus values).
I don't care about the speed, but having to import math (which I otherwise almost never need) is a distraction, and (perhaps more so) I can never remember whether it's modf() or fmod() that I want.
Better, you could use the more obvious:
time.sleep(math.ceil(now) - now)
That "says" as directly as possible that you want the number of seconds needed to reach the next integer value (or 0, if `now` is already an integer).
Yeah, once math is imported the possibilities are endless. :-)
I guess I could use (now - int(now)) in a pinch,
That would need to be
time.sleep(1.0 - (now - int(now)))
I'd use the `ceil` spelling myself, even today -- but I don't suffer "it's better if it's syntax or __builtin__" disease ;-)
assuming int() continues to truncate.
Has anyone suggested to change that? I'm not aware of any complaints or problems due to int() truncating. There have been requests to add new kinds of round-to-integer functions, but in addition to int().
I thought those semantics were kind of poorly specified. But maybe that was long ago (when int() just did whatever (int) did in C) and it's part of the language now. -- --Guido van Rossum (home page: http://www.python.org/~guido/)