Python中统计函数运行耗时的方法
作者:鸪斑兔 时间:2023-03-11 02:17:25
本文实例讲述了Python中统计函数运行耗时的方法。分享给大家供大家参考。具体实现方法如下:
import time
def time_me(fn):
def _wrapper(*args, **kwargs):
start = time.clock()
fn(*args, **kwargs)
print "%s cost %s second"%(fn.__name__, time.clock() - start)
return _wrapper
#这个装饰器可以在方便地统计函数运行的耗时。
#用来分析脚本的性能是最好不过了。
#这样用:
@time_me
def test(x, y):
time.sleep(0.1)
@time_me
def test2(x):
time.sleep(0.2)
test(1, 2)
test2(2)
#输出:
#test cost 0.1001529524 second
#test2 cost 0.199968431742 second
另一个更高级一点的版本是:
import time
import functools
def time_me(info="used"):
def _time_me(fn):
@functools.wraps(fn)
def _wrapper(*args, **kwargs):
start = time.clock()
fn(*args, **kwargs)
print "%s %s %s"%(fn.__name__, info, time.clock() - start), "second"
return _wrapper
return _time_me
@time_me()
def test(x, y):
time.sleep(0.1)
@time_me("cost")
def test2(x):
time.sleep(0.2)
test(1, 2)
test2(2)
希望本文所述对大家的Python程序设计有所帮助。
标签:Python,函数,运行耗时
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp+ajax版四级联动菜单(数据库)
2009-07-03 15:40:00
python打印9宫格、25宫格等奇数格 满足横竖斜相加和相等
2023-08-27 07:55:11
![](https://img.aspxhome.com/file/2023/7/72977_0s.jpg)
Pytorch中如何调用forward()函数
2023-06-14 21:00:24
如何读取一个.ini文件?
2009-11-18 20:58:00
为ABP框架配置数据库
2024-01-19 21:52:05
K8ssandra入门教程之Linux上部署K8ssandra到Kubernetes的过程
2022-04-02 03:12:59
![](https://img.aspxhome.com/file/2023/8/120548_0s.jpg)
基于Python的图像数据增强Data Augmentation解析
2022-12-21 11:50:31
![](https://img.aspxhome.com/file/2023/1/87891_0s.jpg)
超详细,教你用python语言实现QQ机器人制作教程
2023-10-05 10:12:53
![](https://img.aspxhome.com/file/2023/9/82639_0s.png)
对python读取CT医学图像的实例详解
2023-12-29 12:36:37
![](https://img.aspxhome.com/file/2023/0/135210_0s.jpg)
python使用Pyinstaller如何打包整个项目
2021-10-27 04:10:58
![](https://img.aspxhome.com/file/2023/8/94038_0s.jpg)
python 自动提交和抓取网页
2022-11-16 17:47:01
php教程之phpize使用方法
2024-05-02 17:16:46
Python3.5装饰器典型案例分析
2023-03-05 20:32:35
python multiply()与dot使用示例讲解
2021-08-14 19:34:52
electron实现静默打印的示例代码
2024-05-09 15:25:14
![](https://img.aspxhome.com/file/2023/3/126423_0s.png)
基于javascript实现全国省市二级联动下拉选择菜单
2023-09-14 06:08:52
![](https://img.aspxhome.com/file/2023/3/56303_0s.jpg)
如何实现一个python函数装饰器(Decorator)
2023-12-02 19:38:37
Python实现简单猜拳游戏
2022-07-08 04:40:10
![](https://img.aspxhome.com/file/2023/0/124210_0s.jpg)
Vue 3.0中jsx语法的使用
2023-07-02 17:07:17
![](https://img.aspxhome.com/file/2023/6/139936_0s.png)
CentOS7系统搭建LAMP及更新PHP版本操作详解
2024-05-22 10:07:38
![](https://img.aspxhome.com/file/2023/4/124594_0s.png)