首页 > 解决方案 > 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)

标签: pythonwindows

解决方案


像这样使用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)

在上面的示例中,调用将timeoutjoin5 秒后终止线程。如果我们计划多次重用它,我们也可以将它放入装饰器中,如下所示:

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)

推荐阅读