简体   繁体   English

python - >一个while循环一直在运行

[英]python -> time a while loop has been running

i have a loop that runs for up to a few hours at a time. 我有一个循环,一次运行几个小时。 how could I have it tell me how long it has been at a set interval? 我怎么能告诉我它在设定的时间间隔内有多长时间?

just a generic...question 只是一个通用的问题

EDIT: it's a while loop that runs permutations, so can i have it print the time running every 10 seconds? 编辑:这是一个运行排列的while循环,所以我可以打印每10秒运行一次的时间吗?

Instead of checking the time on every loop, you can use a Timer object 您可以使用Timer对象,而不是检查每个循环的时间

import time
from threading import Timer

def timeout_handler(timeout=10):
    print time.time()
    timer = Timer(timeout, timeout_handler)
    timer.start()

timeout_handler()
while True:
    print "loop"
    time.sleep(1)

As noted, this is a little bit of a nasty hack, as it involves checking the time every iteration. 如上所述,这是一个讨厌的黑客,因为它涉及检查每次迭代的时间。 In order for it to work, you need to have tasks that run for a small percentage of the timeout - if your loop only iterates every minute, it won't print out every ten seconds. 为了使它工作,你需要运行一小部分超时的任务 - 如果你的循环只是每分钟迭代一次,它就不会每十秒打印一次。 If you want to be interrupted, you might consider multithreading, or preferably if you are on linux/mac/unix, signals. 如果你想被打断,你可能会考虑多线程,或者最好是你在linux / mac / unix上的信号。 What is your platform? 你的平台是什么?

import time

timeout = 10
first_time = time.time()
last_time = first_time
while(True):
    pass #do something here
    new_time = time.time()
    if  new_time - last_time > timeout:
        last_time = new_time
        print "Its been %f seconds" % (new_time - first_time)

Output: 输出:

Its been 10.016000 seconds
Its been 20.031000 seconds
Its been 30.047000 seconds

There's a very hacky way to do this by using time.asctime(). 使用time.asctime()有一种非常黑客的方法。 You store the asctime before entering the while loop and somewhere in the loop itself. 在进入while循环之前以及循环本身的某个位置存储asctime。 Calculate the time difference between the stored time and the current time and if that difference is 10 seconds, then update the stored time to the current time and print that it's been running. 计算存储时间与当前时间之间的时间差,如果该差值为10秒,则将存储时间更新为当前时间并打印它正在运行的时间。

However, that's a very hacky way to do it as it requires some twisted and boring math. 然而,这是一种非常黑客的方式,因为它需要一些扭曲和无聊的数学。

If your aim is to check the runtime of a specific algorithm, then you're better off using the timeit module 如果您的目标是检查特定算法的运行时间,那么最好使用timeit模块

Hope this Helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM