python计算函数执行时长的方法

更新日期: 2022-09-11阅读: 888标签: Python

python开发,有时需要做性能分析及性能优化,这时就需要记录一些耗时函数执行时间问题,然后针对函数逻辑进行优化。

在python3中一般都有哪些方法呢。

1、使用time.time()

这种方法较简单,但如果想更精确的计算函数的执行时间,会产生精度缺失,没办法统计时间极短的函数耗时。

import time
 
 def func():
     time.sleep(1)
     
 t = time.time()
 func()
 print(f'耗时:{time.time() - t:.4f}s')
 
 耗时:1.0050s

2、使用time.perf_counter()

perf_counter是在python3.3新添加的,返回性能计数器的值,返回值是浮点型,统计结果包括睡眠的时间,单个函数的返回值无意义,只有多次运行取差值的结果才是有效的函数执行时间。

import time
 def func():
     print('hello world')
 t = time.perf_counter()
 func()
 print(f'耗时:{time.perf_counter() - t:.8f}s')
 hello world
 耗时:0.00051790s

3、使用timeit.timeit ()

timeit()函数有5个参数:
   stmt 参数是需要执行的语句,默认为 pass
   setup 参数是用来执行初始化代码或构建环境的语句,默认为 pass
   timer 是计时器,默认是 perf_counter()
   number 是执行次数,默认为一百万
   globals 用来指定要运行代码的命名空间,默认为 None 
 import timeit
 def func():
     print('hello world')
 print(f'耗时: {timeit.timeit(stmt=func, number=1)}')
 hello world
 耗时: 0.0007705999999999824

4、使用装饰器统计

在实际项目代码中,可以通过装饰器方便的统计函数运行耗时。使用装饰器来统计函数执行耗时的好处是对函数的入侵性小,易于编写和修改。

装饰器装饰函数的方案只适用于统计函数的运行耗时,如果有代码块耗时统计的需求就不能用了,这种情况下可以使用 with 语句自动管理上下文。

(1)同步函数的统计

import time 
 def coast_time(func):
     def fun(*args, **kwargs):
         t = time.perf_counter()
         result = func(*args, **kwargs)
         print(f'函数:{func.__name__} 耗时:{time.perf_counter() - t:.8f} s')
         return result
     return fun
 @coast_time
 def test():
     print('hello world')
 if __name__ == '__main__':
     test()

(2)异步函数的统计

import asyncio
 import time
 from asyncio.coroutines import iscoroutinefunction
 def coast_time(func):
     def fun(*args, **kwargs):
         t = time.perf_counter()
         result = func(*args, **kwargs)
         print(f'函数:{func.__name__} 耗时:{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.__name__} 耗时:{time.perf_counter() - t:.8f} s')
         return result
     if iscoroutinefunction(func):
         return func_async
     else:
         return fun
 @coast_time
 def test():
     print('hello test')
     time.sleep(1)
 @coast_time
 async def test_async():
     print('hello test_async')
     await asyncio.sleep(1)
 if __name__ == '__main__':
     test()
     asyncio.get_event_loop().run_until_complete(test_async())       
 hello test
 函数:test 耗时:1.00230700 s
 hello test_async
 函数:test_async 耗时:1.00572550 s

5、with语句统计

通过实现 enter 和 exit 函数可以在进入和退出上下文时进行一些自定义动作,例如连接或断开数据库、打开或 关闭文件、记录开始或结束时间等,例如:我们用来统计函数块的执行时间。

with语句不仅可以统计代码块的执行时间,也可以统计函数的执行时间,还可以统计多个函数的执行时间之和,相比装饰器来说对代码的入侵性比较大,不易于修改,好处是使用起来比较灵活,不用写过多的重复代码。

import asyncio
 import time 
 class CoastTime(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'耗时:{time.perf_counter() - self.t:.8f} s')
 def test():
     print('hello test')
     with CoastTime():
         time.sleep(1)
 async def test_async():
     print('hello test_async')
     with CoastTime():
         await asyncio.sleep(1)
 if __name__ == '__main__':
     test()
     asyncio.get_event_loop().run_until_complete(test_async())
hello test
耗时:1.00723310 s
hello test_async
耗时:1.00366820 s

来源:https://www.toutiao.com/article/7141037855584829990

链接: https://www.fly63.com/article/detial/12114

9 个用于前端开发的Python 框架:JavaScript 替代品

JavaScript 是 Web 开发领域里非常重要的技术之一,并且是每个开发者都必须掌握的技能。而我作为一个开始使用 Python 编程的人

30个非常实用的Python技巧

Python 是机器学习最广泛采用的编程语言,它最重要的优势在于编程的易用性。如果读者对基本的 Python 语法已经有一些了解,那么这篇文章可能会给你一些启发。作者简单概览了 30 段代码,它们都是平常非常实用的技巧

25个超有用的Python代码段

Python是一种通用的高级编程语言。用它可以做许多事,比如开发桌面 GUI 应用程序、网站和 Web 应用程序等。作为一种高级编程语言,Python 还可以让你通过处理常见的编程任务来专注应用程序的核心功能。

如何选择异步Web Python框架

Python在3.4引入了 asyncio 库,3.6新增了关键字 async 和 await ,此后,异步框架迅速发展了起来,性能上能和Node.js比肩,除非是CPU密集型任务,否则没有理由不适用异步框架

11 个优秀的 Python 编译器和解释器

Python 是一门对初学者友好的编程语言,是一种多用途的、解释性的和面向对象的高级语言。它拥有非常小的程序集,非常易于学习、阅读和维护。其解释器可在Windows、Linux 和 Mac OS 等多种操作系统上使用

写 Python 代码不可不知的函数式编程技术

在 Python 中,函数是「头等公民」(first-class)。也就是说,函数与其他数据类型(如 int)处于平等地位。因而,我们可以将函数赋值给变量,也可以将其作为参数传入其他函数

Python 中 3 个不可思议的返回

Python 字典通过检查键值是否相等和比较哈希值来确定两个键是否相同.具有相同值的不可变对象在Python中始终具有相同的哈希值.注意: 具有不同值的对象也可能具有相同的哈希值(哈希冲突)

Python 实现单例模式

而且上面这种方法只有第一次 get_instance() 的时候能给对象传递参数,总之有许多弊端。Python 提供了 __new__ 方法正好完美解决了这个问题,再加上锁,就能实现一个线程安全的单例模式:

常见Python的Web开发框架

web开发框架存在的意义就在于可以快速便捷的构建应用,而不用去在意那些没必要的技术细节,到2020年为止,基于Python创建的的web应用已经非常多了,国外知名的有youtube.com、instagram、reditt、国内有知乎、豆瓣等等

nodejs中怎么调用python函数?

每种语言都有自己的优势,互相结合起来各取所长程序执行起来效率更高或者说哪种实现方式较简单就用哪个,nodejs是利用子进程来调用系统命令或者文件,NodeJS子进程提供了与系统交互的重要接口,其主要API有: 标准输入

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!