1. time.time()
在计算函数执行时间时,这种时最简洁的一种方式,用两个时间戳做减法。
代码片段
Plain Text · 14 lines|
| import time |
| def func(): |
| print('func start') |
| time.sleep(1) |
| print('func end') |
| t = time.time() |
| func() |
| print(f'coast:{time.time() - t:.4f}s') |
| 12 |
结果为:
代码片段
Plain Text · 3 lines|
| func start |
| func end |
| coast:1.0003s |
这种方法很简单,也很常用,但是如果想更精确的计算函数的执行时间,就会产生精度缺失。
2. time.perf_counter() 推荐
示例一中注释掉time.sleep(1),只统计两个 print 函数的执行时间:
代码片段
Plain Text · 14 lines|
| import time |
| def func(): |
| print('func start') |
| # time.sleep(1) |
| print('func end') |
| t = time.time() |
| func() |
| print(f'coast:{time.time() - t:.8f}s') |
| 12345678910111213 |
代码片段
Plain Text · 3 lines|
| func start |
| func end |
| coast:0.0000s |
这就说明time.time() 函数的精度不是特别高,没法统计执行时间极短的函数耗时。
perf_counter 函数是在 python3.3 中新添加的,它返回性能计数器的值,返回值是浮点型,统计结果包括睡眠的时间,单个函数的返回值无意义,只有多次运行取差值的结果才是有效的函数执行时间。
代码片段
Plain Text · 14 lines|
| import time |
| def func(): |
| print('func start') |
| # time.sleep(1) |
| print('func end') |
| t = time.perf_counter() |
| func() |
| print(f'coast:{time.perf_counter() - t:.8f}s') |
| 12345678910111213 |
结果
代码片段
Plain Text · 3 lines|
| func start |
| func end |
| coast:0.00001500s |
结果并不是 0 秒, 而是一个很小的值,这说明 perf_counter() 函数可以统计出 print 函数的执行耗时,并且统计精度要比 time.time() 函数要高,比较推荐作为计时器来使用。
3. timeit.timeit ()
timeit() 函数有 5 个参数,stmt=‘pass’, setup=‘pass’, timer=, number=1000000, globals=None。
- stmt 参数是需要执行的语句,默认为 pass
- setup 参数是用来执行初始化代码或构建环境的语句,默认为 pass
- timer 是计时器,默认是 perf_counter()
- number 是执行次数,默认为一百万
- globals 用来指定要运行代码的命名空间,默认为 None。
代码片段
Plain Text · 13 lines|
| import time |
| import timeit |
| def func(): |
| print('func start') |
| time.sleep(1) |
| print('func end') |
| print(timeit.timeit(stmt=func, number=1)) |
| 123456789101112 |
以上方案中比较推荐使用的是 time.perf_counter() 函数,它具有比较高的精度,同时还被用作 timeit 函数默认的计时器。
4.装饰器统计运行耗时
在实际项目代码中,可以通过装饰器方便的统计函数运行耗时。
代码片段
Plain Text · 23 lines|
| import time |
| def cost_time(func): |
| def fun(*args, **kwargs): |
| t = time.perf_counter() |
| result = func(*args, **kwargs) |
| print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s') |
| return result |
| return fun |
| @cost_time |
| def test(): |
| print('func start') |
| time.sleep(2) |
| print('func end') |
| if __name__ == '__main__': |
| test() |
| 12345678910111213141516171819202122 |
如果有使用异步函数的需求也可以加上:
代码片段
Plain Text · 42 lines|
| import asyncio |
| import time |
| from asyncio.coroutines import iscoroutinefunction |
| def cost_time(func): |
| def fun(*args, **kwargs): |
| t = time.perf_counter() |
| result = func(*args, **kwargs) |
| print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s') |
| return result |
| async def func_async(*args, **kwargs): |
| t = time.perf_counter() |
| result = await func(*args, **kwargs) |
| print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s') |
| return result |
| if iscoroutinefunction(func): |
| return func_async |
| else: |
| return fun |
| @cost_time |
| def test(): |
| print('func start') |
| time.sleep(2) |
| print('func end') |
| @cost_time |
| async def test_async(): |
| print('async func start') |
| await asyncio.sleep(2) |
| print('async func end') |
| if __name__ == '__main__': |
| test() |
| asyncio.get_event_loop().run_until_complete(test_async()) |
| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
使用装饰器来统计函数执行耗时的好处是对函数的入侵性小,易于编写和修改。
装饰器装饰函数的方案只适用于统计函数的运行耗时,如果有代码块耗时统计的需求就不能用了,这种情况下我们可以使用 with 语句自动管理上下文。
5. with 语句统计运行耗时
通过实现 enter 和 exit 函数可以让我们在进入上下文和退出上下文时进行一些自定义动作,例如连接 / 断开数据库、打开 / 关闭文件、记录开始 / 结束时间等等,这里我们用来统计函数块的执行时间。
代码片段
Plain Text · 35 lines|
| import asyncio |
| import time |
| class CostTime(object): |
| def __init__(self): |
| self.t = 0 |
| def __enter__(self): |
| self.t = time.perf_counter() |
| return self |
| def __exit__(self, exc_type, exc_val, exc_tb): |
| print(f'cost time:{time.perf_counter() - self.t:.8f} s') |
| def test(): |
| print('func start') |
| with CostTime(): |
| time.sleep(2) |
| print('func end') |
| async def test_async(): |
| print('async func start') |
| with CostTime(): |
| await asyncio.sleep(2) |
| print('async func end') |
| if __name__ == '__main__': |
| test() |
| asyncio.get_event_loop().run_until_complete(test_async()) |
| 12345678910111213141516171819202122232425262728293031323334 |
with 语句不仅可以统计代码块的执行时间,也可以统计函数的执行时间,还可以统计多个函数的执行时间之和,相比装饰器来说对代码的入侵性比较大,不易于修改,好处是使用起来比较灵活,不用写过多的重复代码。