python - Windows 上 Python 中的计时器
问题描述
如果我在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)
解决方案
像这样使用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)
推荐阅读
- django - 在将关系添加到 django 中的数据库之前添加关系
- vba - VBA 'set typelib = createobject(“scriptlet.typelib”)' 权限被拒绝 - 同样的问题,新的原因?
- python - 使用组框将焦点设置在应用程序中的按钮上
- java - 即使 sql 查询不应该返回任何记录,JUnit 测试仍然通过
- arcore - Arcore:如何获得放置在表面上的图像的尺寸?
- python - DLIB:ImportError:/usr/local/cuda/lib64/libcudnn.so.7:文件太短
- ssl - SSL Labs:错误的顺序,额外的证书
- mysql - MySQL 查询需要更多时间来获取数据 [MySQL]
- delphi - Delphi 发送带有 TIdHttp 和特殊字符的 POST
- kubernetes - 可以在 GKE 上使用 Google Cloud IAM 设置命名空间级别权限吗?