【问题标题】:How can I get python to print out the current elapsed time while a function is running?如何让 python 在函数运行时打印出当前经过的时间?
【发布时间】:2017-11-06 16:13:53
【问题描述】:

所以我目前有 python 打印一个函数在完成运行后运行多长时间,如下所示:

import time
t = time.time()
# do something in here
print "\n Time Taken: %.3f sec" % (time.time()-t)

但我想显示自函数启动以来已经过去的实时时间,但我无法找到实现这一目标的方法。

例如在终端中,我希望它说:

Working on xFunction. Time Elapsed 72.485 sec... (live updated time)
xFunction Has finished.
Time Taken: 1152.546 sec

任何帮助将不胜感激。

【问题讨论】:

  • 您可以使用os.fork()为其创建一个新线程。
  • 请注意,OP 似乎想要 live 显示经过的时间(正如标题已经暗示的那样,但问题文本没有)。
  • threading
  • 你为什么不把打印输出放在函数有的任何语句之间?
  • 请显示一个函数以及你打算如何调用它。

标签: python


【解决方案1】:

我已经修改了 @import_random 的代码,以便能够在代码执行过程中随时探测经过的时间,方法是包装 2 个用于初始化和完成 ETC 的函数:

import time
import threading

class ElapsedTimeThread(threading.Thread):
    """"Stoppable thread that prints the time elapsed"""

    
    def __init__(self):
        super(ElapsedTimeThread, self).__init__()
        self._stop_event = threading.Event()
        self.thread_start = time.time()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

    def getStart(self):
        return self.thread_start
    
    def getCurrentTime(self):
        print("\rElapsed Time {:.3f} s. ".format(time.time()-self.thread_start), end="", flush=True )
        
    def run(self):
        self.thread_start = time.time()
        while not self.stopped():
            print("\rElapsed Time {:.3f} s. ".format(time.time()-self.thread_start), end="", flush=True)
            #include a delay here so the thread doesn't uselessly thrash the CPU
            time.sleep(0.01)

def startTimeCounter():    
    threadTimer = ElapsedTimeThread()
    threadTimer.start()
    return threadTimer

def stopTimeCounter(threadTimeCounter):
    print() # empty print() to output a newline
    print("Finished in {:.3f} s. ".format(time.time()-threadTimeCounter.getStart()))
    threadTimeCounter.stop()
    threadTimeCounter.join()

【讨论】:

    【解决方案2】:

    这是一个带有线程的示例,该线程将打印自启动以来经过了多少时间,并且可以从主循环中停止。

    import time
    import threading
    
    class ElapsedTimeThread(threading.Thread):
        """"Stoppable thread that prints the time elapsed"""
        def __init__(self):
            super(ElapsedTimeThread, self).__init__()
            self._stop_event = threading.Event()
    
        def stop(self):
            self._stop_event.set()
    
        def stopped(self):
            return self._stop_event.is_set()
    
        def run(self):
            thread_start = time.time()
            while not self.stopped():
                print("\rElapsed Time {:.3f} seconds".format(time.time()-thread_start), end="")
                #include a delay here so the thread doesn't uselessly thrash the CPU
                time.sleep(0.01)
    
    if __name__ == "__main__":
        start = time.time()
        thread = ElapsedTimeThread()
        thread.start()
        # do something
        time.sleep(5)
        # something is finished so stop the thread
        thread.stop()
        thread.join()
        print() # empty print() to output a newline
        print("Finished in {:.3f} seconds".format(time.time()-start))
    

    这给出了以下输出,已用时间从零开始计数并被覆盖:

    J:\>python thr_time.py
    Elapsed Time 5.000 seconds
    Finished in 5.001 seconds
    

    请注意,此代码在 Python 3 中。有关停止线程 herehere 的更多信息。

    如果您想澄清任何部分,请告诉我。

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 2023-03-05
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      相关资源
      最近更新 更多