[英]How can I get python to print out the current elapsed time while a function is running?
So I currently have python printing how long it took for a function to run after its done running with something like:所以我目前有 python 打印一个函数在运行完成后需要多长时间运行,例如:
import time
t = time.time()
# do something in here
print "\n Time Taken: %.3f sec" % (time.time()-t)
but I want to show the live time that has passed since the function has started, and I cant quite figure out a way to get that to happen.但我想显示自函数启动以来已经过去的实时时间,我无法找到一种方法来实现它。
for example in a terminal I want it to say something like:例如在终端中,我希望它说:
Working on xFunction. Time Elapsed 72.485 sec... (live updated time)
xFunction Has finished.
Time Taken: 1152.546 sec
Any help would be appreciated.任何帮助将不胜感激。
Here's an example with a thread that will print how much time has elapsed since it started and can be stopped from the main loop.这是一个带有线程的示例,该线程将打印自启动以来已经过去了多少时间,并且可以从主循环中停止。
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))
This gives the following output, with the Elapsed Time counting up from zero and being overwritten:这给出了以下输出,其中Elapsed Time从零开始计数并被覆盖:
J:\>python thr_time.py
Elapsed Time 5.000 seconds
Finished in 5.001 seconds
Note that this code is in Python 3. More info on stopping threads here & here .请注意,此代码在 Python 3 中。有关在此处和此处停止线程的更多信息。
Let me know if you'd like clarification on any portions.如果您想对任何部分进行澄清,请告诉我。
I've modified @import_random 's code to enable the ability to probe elapsed time at any time during the execution of code, by wrapping 2 functions for initialization and finalization of ETC:我修改了 @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.