简体   繁体   English

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

[英]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.

相关问题 如何使用python打印以毫秒为单位的经过时间 - How can I print elapsed time in ms using python 在 python 中运行 http_serve_forever() 时,如何按时间打印字符串 - How can i do print string by time while i running http_serve_forever() in python 如何测量 Python 中经过的时间? - How do I measure elapsed time in Python? 如何在python中基于文本的应用程序中与其他函数交互时获得经过的时间 - how to get the elapsed time while interacting with other functions in a text-based application in python 如果在Python中运行该程序时已更改了当前本地时间,如何找到? - How can the current local time be found if it has been changed while the program is running in Python? 在 SpeechRecognition 中,如果通过 adjust_for_ambient_noise 设置,我如何才能打印出当前设置的能量阈值 - In SpeechRecognition how can I get a print out of the current set energy threshold if set it by adjust_for_ambient_noise 我怎样才能摆脱这个嵌套的while循环? (Python) - How can i get out of this nested while loop? (Python) 如何从 cpp 获取 python function 的打印 - How can I get the print of python function from cpp 如何测量python与tkinter按下按钮之间的经过时间? - How can I measure elapsed time between the press of buttons in python with tkinter? 如何在python中查找任何函数或任何例程的总经过时间 - How to Find the total elapsed time for any function or any routine in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM