4

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.

kuthedk
  • 153
  • 1
  • 11

2 Answers2

6

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.

import random
  • 3,054
  • 1
  • 17
  • 22
0

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 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()
Miguel Tomás
  • 1,714
  • 1
  • 13
  • 23