python 实现计时器

方式一:建立一个类

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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:
raise RuntimeError('Already started')
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 timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
func(*args, **kwargs)
end = time.perf_counter()
print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
return wrapper

演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from timer import Timer


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


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

# Use 2: As a context manager
with Timer() as t:
countdown(1000000)
print(t.elapsed) # 0.0440638

方式二:装饰器

代码

1
2
3
4
5
6
7
8
9
10
11
import time
from functools import wraps

def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
func(*args, **kwargs)
end = time.perf_counter()
print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
return wrapper

演示

1
2
3
4
5
6
7
8
9
from timer import timer

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


countdown(1000000) # __main__.countdown : 0.0442

注意事项

  • time.perf_counter() 记录的是钟表时间,包含了所有休眠时间
  • time.process_time() 只计算该进程所花费的CPU时间
  • 单位是秒