pythontimerpython-multithreadingelapsedtime

Retrieving remaining time from python timer


Looking for simple approach to obtaining remaining and elapsed time from python timer. Currently have (based on github source for threading.Timer and previous post):

import threading
import time

class CountdownTimer(threading.Thread):
    def __init__(self, interval, function, args=None, kwargs=None):
        threading.Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()
        self.started_at = None

    def cancel(self):
        self.finished.set()

    def elapsed(self):
        return time.time() - self.started_at

    def remaining(self):
        return self.interval - self.elapsed()

    def run(self):
        self.started_at = time.time()
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

Does this look reasonably effective (do not need accuracy in excess of what threading.Timer currently provides)?


Solution

  • perf_counter()

    import time
    
    start = time.perf_counter()
    time.sleep(2)
    finish = time.perf_counter()
    print(f'Finished in {round(finish-start, 2)} second(s)')
    
    

    Advantages of perf_counter() :

    1. perf_counter() will give you more precise value than time.clock() function .

    2. From Python3.8 time.clock() function will be deleted and perf_counter will be used.

    3. We can calculate float and integer both values of time in seconds and nanoseconds.