【问题标题】:Time of execution of a command while is running运行时执行命令的时间
【发布时间】:2018-01-11 07:48:54
【问题描述】:

我在一行中有一个命令(Fit.perform() 来自import xspec,但没关系,因为这个问题很笼统,也可以应用于其他 python 命令)需要一段时间才能完成。

我只是想知道命令正在运行时的执行时间,所以当它尚未完成执行时。 如果我想在命令执行期间停止命令,这是必要的,例如因为它需要太多时间才能结束。

所以,我需要这样的东西:

if **you_are_taking_so_much_time**:
    do_something_else

不可能使用timetimeit 之类的方法,因为它们仅在命令执行结束时计算时间,而不是在命令运行时计算时间。

有可能吗?

我在 MacOS 上使用 python 2.7。

【问题讨论】:

  • 您将需要使用监控线程。

标签: python python-2.7 time xspec


【解决方案1】:

您将不得不使用监控线程:

import threading
import time

done = False

def longfun():
    global done
    print("This will take some time.")
    time.sleep(60)
    done = True

def monitor():
    global done
    timeout = 10
    print("Wait until timeout.")
    while not done and timeout > 0:
        time.sleep(1)
        timeout -= 1

lt = threading.Thread(target=longfun)
lt.start()
mt = threading.Thread(target=monitor)
mt.start()

mt.join()
if done == False:
    print("Long thread not done yet. Do something else.")

lt.join()

请注意,这会等到“长”线程完成。您没有提到要停止长时间运行的操作。如果这样做,则必须在线程中正确实现它,包括启动/停止/进度功能(通常这与使用 running 位的 while 循环一起工作,以查看它是否应该继续。

【讨论】:

  • 谢谢你的回答,但我必须把我的命令Fit.perform() 放在哪里?我只有一条线路 (Fit.perform()) 需要监控。
  • @AlessandroPeca,你把它代替了time.sleep(60) 调用。我把它作为一个占位符,用于长时间运行的阻塞操作。
  • 对不起,我尝试了各种方法,似乎都不起作用,你可以给我一个例子,在代码中间插入监控功能?
【解决方案2】:

像这样:

import time,thread
def test_me(hargs):
    func,args,timeout = hargs
    start_time = time.time()
    thread.start_newthread(func,args)
    while True :
        if My_expected_value:#where store this ?
            print "well done !"
            break
        elif time.time() > (timeout + start_time) :
            print "oh! to late, sorry !"
            break
        time.sleep(timeout/100)
thread.start_newthread(test_me,((func,args,timeout),))

重要警告:非冻结应用程序需要使用线程,为此获得了 3 个线程:1-主应用程序,2-test_me,3-您的函数(func)

不要忘记向你的函数添加外部变量(用于杀死你的函数线程)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2015-01-07
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多