Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get python to print out the current elapsed time while a function is running?

Tags:

python

So I currently have python printing how long it took for a function to run after its done running with something like:

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.

like image 649
kuthedk Avatar asked Oct 21 '25 14:10

kuthedk


1 Answers

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:

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.

Let me know if you'd like clarification on any portions.

like image 137
import random Avatar answered Oct 24 '25 04:10

import random



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!