如果我在 for 循环中有一个被多次调用的函数,而该函数有时运行了太多时间,我该如何为每个函数调用使用一个计时器(设置和重置)每次计时器)?
它看起来像:
def theFunction(*args):
#some code (timer is on)
#In this point time is out, break and exit function
#Timer is reseted
for i in range(0,100):
theFunction(*args)
答案 0 :(得分:2)
像这样使用time
模块:
import time
time_start = time.time()
#Do function stuff
time_stop = time.time()
#Check your time now
timed_segment = time_stop - time_start
#Repeat if needed
要在for循环中多次运行此命令,您将需要在列表中添加时间,如下所示:
import time
def function():
times_list = []
for x in range(10)
time_start = time.time()
#Do function stuff
time_stop = time.time()
#Check your time now
timed_segment = time_stop - time_start
times_list.append(timed_segment)
#Repeat as many times as needed
return times_list
如果您想在一段时间后break
,可以使用while
循环,如下所示:
import time
def function():
times_list = []
time_start = time.time()
time_end = time.time()
while time_end - time_start < 10: #after 10 seconds the while loop will time out
#Your function does stuff here
time_end = time.time()
#Next, append times to a list if needed
time_list.append(time_start - time_end)
return times_list
要在一定时间后停止该功能,而不管它在哪里,我们可以像这样使用threading
:
import threading
from time import sleep
def do_stuff():
sleep(10)
print("1 + 2")
return
t = threading.Thread(target=do_stuff)
t.start()
t.join(timeout = 5)
在上面的示例中,在timeout
中调用join
将在5秒钟后杀死线程。如果我们打算像这样多次重复使用它,也可以将其放入装饰器中:
import threading
from time import sleep
def timeout(func):
def inner_func(*nums, **kwargs):
t = threading.Thread(target=func, args=(*nums,))
t.start()
t.join(timeout=5)
return inner_func
@timeout
def do_stuff(a,b):
sleep(3)
print(a+b)
return
do_stuff(1,3)
答案 1 :(得分:1)
还有一个名为timeit
的模块,它可以测量小代码段的执行时间。我相信您也可以使用它。我从未使用过该模块,但应该可以使用。
这是指向文档页面的链接。看看:: https://docs.python.org/2/library/timeit.html
答案 2 :(得分:0)
为了实现高度可重用性和易于实现,我建议-
使用装饰器-
from time import time
def time_it(func):
def wrapper(*args, **kwargs):
a=time()
func(*args, **kwargs)
print(a-time())
return wrapper
@time_it
def foo(s='this works'):
print(s)
foo()
使用profile.run-https://docs.python.org/2/library/profile.html#module-profile