Below is the code of a simple timer that prints out a new number in the command line every 0.1 sec, and -- simultaneously -- awaits for a keypress (Enter). As soon as Enter is pressed, the timer is switched into pause, stops printing and waits for another Enter keypress that would resume counting / printing.
The problem I face is that while in the 'pause' state, CPU consumption grows to almost 100% (and seems to be below 1% while running / printing out).
Why is it? What am I doing wrong?
Here goes the code:
import time, thread, sys
time_passed = 0
l = []
trig = True
def input(l):
""" Waits for a keypress """
raw_input()
l.append(None)
def timer():
""" Prints out a number every millisecond """
global time_passed
time.sleep(.1)
time_passed += 1
sys.stdout.write(format(time_passed)+"\r")
sys.stdout.flush()
def running():
""" Toggles play/pause state if Enter is pressed """
global trig, l
while trig:
timer()
if l:
l = []
trig = False
return trig, l
def stopped():
""" Toggles pause/play state if Enter is pressed """
global trig, l
while not trig:
if l:
l = []
trig = True
return trig, l
def main():
""" Waits for a keypress while either running or stopping the timer """
global l, trig
while True:
thread.start_new_thread(input, (l,))
if trig: # The timer is running
running()
else: # The timer is stopped
stopped()
main()
Thank you.