2017-06-05 34 views
2

所以我现在有蟒蛇打印了多长时间了功能对其做的东西,如运行后,运行:如何在函数运行时打印出当前运行时间?

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 

任何帮助,将不胜感激。

+0

你可以用'os.fork()'为它启动一个新的线程。 –

+2

请注意,OP似乎需要经过时间的_live_显示(正如标题已经表明的,但问题文本没有)。 – handle

+1

或['threading'](https://docs.python.org/3/library/threading.html)。 – handle

回答

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

让我知道你是否想要澄清任何部分。