下面是一个简单计时器的代码,它每0.1秒在命令行中输出一个新数字,并且 - 同时 - 等待按键(回车)。按下Enter后,定时器将切换为暂停,停止打印并等待另一个将重新开始计数/打印的Enter按键。
我面临的问题是,在“暂停”期间。状态,CPU消耗增长到几乎100%(并且在运行/打印时似乎低于1%)。
为什么?我做错了什么?
这里是代码:
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()
谢谢。
答案 0 :(得分:1)
好吧,如果它在"停止"说你运行这个:
def stopped():
""" Toggles pause/play state if Enter is pressed """
global trig, l
while not trig:
if l:
l = []
trig = True
return trig, l
此循环没有暂停/等待。因此它在没有返回系统的情况下全速运行,而在running
内,您可以调用time.sleep
。将time.sleep(0.1)
放在if
之前将使其按预期工作。
也是一个友好的个人笔记,你可以稍微重构一下。使用全局变量的两个具有相同描述的函数使得它有点难以理解=)。
我做了类似的事情:
import time, thread, sys, threading
time_passed = 0
l = []
def input(l):
""" Waits for a keypress """
raw_input()
l.append(None)
def timer():
""" Prints out a number every millisecond """
global time_passed
time_passed += 1
sys.stdout.write(format(time_passed)+"\r")
sys.stdout.flush()
def running(state):
""" Toggles play/pause state if Enter is pressed """
global l
while True:
time.sleep(.1)
if state:
timer()
if l:
l = []
state = not state
return state
def main():
""" Waits for a keypress while either running or stopping the timer """
global l
state = True
while True:
thread.start_new_thread(input, (l,))
state = running(state)
main()
我想如何更好地发出切换信号。我不知道从函数返回的想法,你不需要真正从运行中返回,只需翻转状态。但我想这只是个人偏好。