# Timer

> 原文： [https://www.fuzzingbook.org/html/Timer.html](https://www.fuzzingbook.org/html/Timer.html)

本笔记本中的代码有助于测量时间。

**前提条件**

*   该笔记本需要对Python的高级概念有一些了解，特别是
    *   类
    *   Python `with`语句
    *   测量时间

## 内容提要

要使用本章中提供的代码来[，请编写](Importing.html)

```py
>>> from [fuzzingbook.Timer](Timer.html) import <identifier>

```

然后利用以下功能。

`Timer`类允许您测量经过的实时时间。 它的典型用法是与`with`子句结合使用：

```py
>>> with Timer() as t:
>>>     some_long_running_function()
>>> t.elapsed_time()
0.04299802700006694

```

## 测量时间

`Timer`类允许测量某些代码执行期间的经过时间。

```py
import [fuzzingbook_utils](https://github.com/uds-se/fuzzingbook/tree/master/notebooks/fuzzingbook_utils)

```

```py
import [time](https://docs.python.org/3/library/time.html)

```

```py
def clock():
    try:
        return time.perf_counter()  # Python 3
    except:
        return time.clock()         # Python 2

```

```py
class Timer(object):
    # Begin of `with` block
    def __enter__(self):
        self.start_time = clock()
        self.end_time = None
        return self

    # End of `with` block
    def __exit__(self, exc_type, exc_value, tb):
        self.end_time = clock()

    def elapsed_time(self):
        """Return elapsed time in seconds"""
        if self.end_time is None:
            # still running
            return clock() - self.start_time
        else:
            return self.end_time - self.start_time

```

这是一个例子：

```py
def some_long_running_function():
    i = 1000000
    while i > 0:
        i -= 1

```

```py
print("Stopping total time:")
with Timer() as t:
    some_long_running_function()
print(t.elapsed_time())

```

```py
Stopping total time:
0.04350709200025449

```

```py
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())

```

```py
Stopping time in between:
3.072999788855668e-06
6.375699922500644e-05
0.00032886200006032595
0.0003797529998337268
0.0003976899997724104
0.00041616799990151776
0.0004380209993541939
0.00045481599954655394
0.00046889599980204366
0.00048251899988827063

```

就是这样-伙计们-尽情享受吧！

>