[英]How can I get python to print out the current elapsed time while a function is running?
所以我目前有 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
任何幫助將不勝感激。
這是一個帶有線程的示例,該線程將打印自啟動以來已經過去了多少時間,並且可以從主循環中停止。
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))
這給出了以下輸出,其中Elapsed Time從零開始計數並被覆蓋:
J:\>python thr_time.py
Elapsed Time 5.000 seconds
Finished in 5.001 seconds
請注意,此代碼在 Python 3 中。有關在此處和此處停止線程的更多信息。
如果您想對任何部分進行澄清,請告訴我。
我修改了 @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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.