正在从 python 计时器中检索剩余时间

Retrieving remaining time from python timer

正在寻找从 python 计时器获取剩余时间和经过时间的简单方法。目前有(基于 github threading.Timer 和之前 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()

这看起来是否相当有效(不需要超过 threading.Timer 当前提供的精度)?

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

perf_counter() 的优点:

  1. perf_counter() 会给你比 time.clock() 函数更精确的值。

  2. From Python3.8 time.clock()函数将被删除,将使用perf_counter

  3. 我们可以计算以秒和纳秒为单位的浮点数和整数时间值。