from temp4 import f1
from temp5 import f2
from timeit import default_timer as timer
start = timer()
while (timer()-start)<10:
f1()
print timer()-start
while (timer()-start)<20: #add timings here
f2()
print timer()-start
import signal
import time
def task(name):
"""Generic task print out name once a second."""
while True:
print(name)
time.sleep(1)
class Stop(Exception):
"""Raised to stop a running task."""
pass
def onAlarm(signum, frame):
"""Alarm signal handler."""
raise Stop
def run(function, seconds):
"""Run a function for a specified number of seconds."""
# install our alarm handler
savedHandler = signal.signal(signal.SIGALRM, onAlarm)
# request an alarm after the specified numbers of seconds
signal.setitimer(signal.ITIMER_REAL, seconds)
# run the function
try:
function()
except Stop:
pass
# restore the saved timeout handler
signal.signal(signal.SIGALRM, savedHandler)
# run hello for 6 seconds
run(lambda: task("hello"), 6)
# run hello1 for 4 seconds
run(lambda: task("hello1"), 4)
让我定义两个python脚本temp4.py和temp5.py。内容:
临时4.py
临时5.py
最终脚本temp5.py。这将测量时间并相应地运行脚本。改变时代。在这里,两个脚本都将运行10秒。你知道吗
请把第二次加到计时器上。所以第一次是60,第二次是100。你知道吗
您可以在代码运行一段时间后使用警报来中断代码。优点是运行的代码不需要知道时间限制。缺点是它没有机会优雅地终止(尽管您可以捕获Stop异常来终止)。你知道吗
相关问题 更多 >
编程相关推荐