我正在用 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()