Windows上Python中的计时器

2024-10-01 15:35:18 发布

您现在位置: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)

Tags: 函数inforisondef时间args
3条回答

还有另一个名为timeit的模块,它可以测量小代码段的执行时间。我相信你也可以用这个。我从未使用过该模块,但它应该可以工作。

这是到doc页面的链接。看一看::https://docs.python.org/2/library/timeit.html

请参见How to use timeit module

使用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循环中多次运行此命令,您需要将时间追加到列表中,如下所示:

^{pr2}$

如果您想在一定时间后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)

在上面的例子中,在join中调用timeout将在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)

为了提高可重用性和易于实现,我建议-

相关问题 更多 >

    热门问题