【问题标题】:Retrieving remaining time from python timer从python计时器中检索剩余时间
【发布时间】:2020-05-25 16:47:47
【问题描述】:

寻找从 python 计时器获取剩余时间和经过时间的简单方法。目前有(基于github source for threading.Timer和之前的帖子):

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 当前提供的精度)?

【问题讨论】:

  • 是的,这是一个好方法。这一切都取决于您的需要。一般来说,如果我想通过我的程序监控时间,我只需使用time.time()函数。

标签: python timer python-multithreading elapsedtime


【解决方案1】:

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. 从 Python3.8 开始,time.clock() 函数将被删除,perf_counter 将被使用。

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

【讨论】:

  • 谢谢,这很简单,而且精度更高。
  • 采用这种方法,因为类方法对我的目的来说太过分了,正如@xaander1 所提到的,解决方案提供了额外的解决方案。再次感谢!
猜你喜欢
  • 2018-02-02
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多