3

Input: array of float time values (in seconds) relative to program start. [0.452, 0.963, 1.286, 2.003, ... ]. They are not evenly spaced apart.

Desired Output: Output text to console at those times (i.e. printing '#')

My question is what is the best design principle to go about this. Below is my naive solution using time.time.

times = [0.452, 0.963, 1.286, 2.003]
start_time = time.time()
for event_time in times:
    while 1:
        if time.time() - start_time >= event_time:
            print '#'
            break

The above feels intuitively wrong using that busy loop (even if its in its own thread).

I'm leaning towards scheduling but want to make sure there aren't better design options: Executing periodic actions in Python

There is also the timer object: timers

Edit: Events only need 10ms precision, so +/- 10ms from exact event time.

Community
  • 1
  • 1
Grant G
  • 49
  • 1
  • 4

1 Answers1

0

A better pattern than busy waiting might be to use time.sleep(). This suspends execution rather than using the CPU.

time_diffs = [0.452, 0.511, 0.323, 0.716]
for diff in time_diffs:
    time.sleep(diff)
    print '#'

Threading can also be used to similar effect. However both of these solutions only work if the action you want to perform each time the program 'restarts' takes negligible time (perhaps not true of printing).

That being said no pattern is going to work if you are after 10ms precision and want to use Python on a standard OS. I recommend this question on Real time operating via Python which explains both that GUI events (i.e. printing to a screen) are too slow and unreliable for that level of precision, that your typical OSs where Python is run do not guarantee that level of precision and that Python's garbage collection and memory management also play havoc if you want 'real-time' events.

blueenvelope
  • 699
  • 7
  • 15