我在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 :(得分:1)
如果您只是在self.start()
结尾处添加对update
的来电,那么我认为它会按照您的预期方式运作。
您看到当前代码存在问题的原因是您每次更新时都会将_startTime
的总偏移量添加到now()
,但您只需要now()
之间的差异当计时器在第一次通话时启动。在后续通话中,您希望now()
与之前调用update
之间存在差异。