如何在函数运行时让python打印出当前经过的时间?

时间:2017-06-05 19:45:44

标签: python

所以我目前有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

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

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

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中。有关停止线程的更多信息here& here

如果您想澄清任何部分,请与我们联系。

答案 1 :(得分:0)

我修改了 @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()