# 13.13 实现一个计时器¶

## 解决方案¶

`time` 模块包含很多函数来执行跟时间有关的函数。 尽管如此，通常我们会在此基础之上构造一个更高级的接口来模拟一个计时器。例如：

```import time

class Timer:
def __init__(self, func=time.perf_counter):
self.elapsed = 0.0
self._func = func
self._start = None

def start(self):
if self._start is not None:
self._start = self._func()

def stop(self):
if self._start is None:
raise RuntimeError('Not started')
end = self._func()
self.elapsed += end - self._start
self._start = None

def reset(self):
self.elapsed = 0.0

@property
def running(self):
return self._start is not None

def __enter__(self):
self.start()
return self

def __exit__(self, *args):
self.stop()
```

```def countdown(n):
while n > 0:
n -= 1

# Use 1: Explicit start/stop
t = Timer()
t.start()
countdown(1000000)
t.stop()
print(t.elapsed)

# Use 2: As a context manager
with t:
countdown(1000000)

print(t.elapsed)

with Timer() as t2:
countdown(1000000)
print(t2.elapsed)
```

## 讨论¶

```t = Timer(time.process_time)
with t:
countdown(1000000)
print(t.elapsed)
```

`time.perf_counter()``time.process_time()` 都会返回小数形式的秒数时间。 实际的时间值没有任何意义，为了得到有意义的结果，你得执行两次函数然后计算它们的差值。