1

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)?

robohobo
  • 25
  • 4
  • yes it's a good approach. It all depends on your need. Generally, if I want to monitore time through my programs, I simply use `time.time()` function. – pyOliv May 25 '20 at 17:34

1 Answers1

0

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.

xaander1
  • 1,064
  • 2
  • 12
  • 40
  • Thank you, that is simple and would give higher precision. – robohobo May 25 '20 at 19:35
  • Went with this approach as class approach was overkill for my purpose, and as @xaander1 mentions, solution provides additional resolution. Thanks again! – robohobo May 27 '20 at 00:25