【问题标题】:How should an accumulator in a Python clock be handled correctly?如何正确处理 Python 时钟中的累加器?
【发布时间】:2014-12-22 03:15:13
【问题描述】:

我正在用 Python 编写一个可以启动、停止和重置的小时钟对象。我很难知道如何正确跟踪时间的累积。现在,更新过程的编写方式,时钟累积了太多时间(因为调用了更新方法)。我不确定如何编写它以累积正确的时间。

import time
import datetime

class Clock(object):

    def __init__(
        self,
        name  = None,
        start = True
        ):
        self._name  = name
        self._start = start # Boolean start clock on instantiation
        # If a global clock list is detected, add a clock instance to it.
        if "clocks" in globals():
            clocks.add(self)
        self.reset()
        if self._start:
            self.start()

    def start(self):
        self._startTime = datetime.datetime.utcnow()

    def stop(self):
        self._startTime = None

    # Update the clock accumulator.
    def update(self):
        self.accumulator += (
            datetime.datetime.utcnow() - self._startTime
        )

    def reset(self):
        self.accumulator = datetime.timedelta(0)
        self._startTime  = None

    # If the clock has a start time, add the difference between now and the
    # start time to the accumulator and return the accumulation. If the clock
    # does not have a start time, return the accumulation.
    def elapsed(self):
        if self._startTime:
            self.update()
        return(self.accumulator)

    def time(self):
        return(self.elapsed().total_seconds())

clock = Clock()
print clock.time()
print "starting"; clock.start()
for i in range(4):
    time.sleep(3)
    print clock.time()
print "stopping"; clock.stop()
for i in range(4):
    time.sleep(3)
    print clock.time()
print "starting"; clock.start()
for i in range(4):
    time.sleep(3)
    print clock.time()
print "resetting"; clock.reset()
print clock.time()

【问题讨论】:

  • 您的预期输出时间是多少?稍作改动,我就可以输出0, 3, 6, 9, 12, 12, 12, 12, 12, 15, 18, 21, 24, 0。这是需要的吗?
  • 你为什么要添加自开始以来的时间,而不是将其设置为自开始以来的时间?
  • @Amber,你是对的,除了 start 的写法之外,如果 update 只是设置 self.accumulator 而不是添加到它,那么 start 基本上会导致重启。显然,可以这样写,但事实并非如此,但就目前而言,它会随着这种变化而崩溃。

标签: python methods clock accumulate


【解决方案1】:

如果您只是在update 末尾添加对self.start() 的调用,那么我认为它会按照您的预期方式工作。

您看到当前代码问题的原因是您每次更新时都将总偏移量从 _startTime 添加到 now(),但您只想要 now() 和计时器启动时间之间的差异第一个电话。在随后的调用中,您需要 now() 和上一次调用 update 之间的差异。

【讨论】:

  • 啊,就是这样。感谢您对此的帮助。根据您的 cmets,我添加了另一个时间数据属性来记录最后一次更新调用的时间。这样,我就不会破坏开始时间信息(我希望能够打印出来)。
猜你喜欢
  • 2016-04-02
  • 1970-01-01
  • 2020-09-25
  • 2022-01-16
  • 2021-07-31
  • 2013-09-09
  • 2019-08-26
  • 2021-08-19
  • 2018-05-27
相关资源
最近更新 更多