温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在python中使用cProfile性能测量工具

发布时间:2021-03-23 16:33:55 来源:亿速云 阅读:223 作者:Leah 栏目:开发技术

如何在python中使用cProfile性能测量工具?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

命令行:

cProfile -s tottime your_program.py

结果如下:

ncalls tottime percall cumtime percall filename:lineno(function)
  66  0.001  0.000  11.850  0.180 base.py:228(micro_service)
  66  0.003  0.000  11.849  0.180 tools.py:557(micro_service)
 1056  0.001  0.000  11.073  0.010 connection.py:463(drain_events)
 1056  0.015  0.000  11.072  0.010 connection.py:466(blocking_read)
 1056  0.008  0.000  10.920  0.010 transport.py:233(read_frame)
 3168  0.014  0.000  10.908  0.003 transport.py:370(_read)
 3168  10.892  0.003  10.892  0.003 {method 'recv' of '_socket.socket' objects}
  66  0.001  0.000  9.814  0.149 rpc.py:350(__call__)
  66  0.001  0.000  8.395  0.127 rpc.py:329(result)

块分析:

上面属于文件分析,但是我们可能只对部分代码感兴趣,那么只需要在这部分代码的前后加上下面这两段代码即可:

import cProfile
cp = cProfile.Profile()
cp.enable()
YOUR CODE
cp.disable()
cp.print_stats()

结果与全代码分析的类似,但是只包含你感兴趣的部分。

行分析:

行分析需要安装line_profiler:

pip install line_profiler
@profile
def class_name()
	pass

然后在命令行输入:

kernprof -l -v your_code.py
-l 逐行分析
-v 立即查看结果

示例:

from cProfile import Profile as profile 
from pstats import Stats 
def (): 
	p = profile() 
	p.snapshot_stats() 
	p.enable() 
	
	p.disable() 
	p.print_stats(2) # 按照调用累加总耗时累加排序,即将最耗时的函数最优先
	p.dump_stats("call.log")

关于如何在python中使用cProfile性能测量工具问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI