###################

#Python脚本性能剖析

###################



cProfile/profile/hotshot用于统计Python脚本各部分运行频率和耗费时间等统计信息。pstats可用于格式化这些信息



cProfile,属C扩展。开销较小,适合剖析长时间执行的Python程序,推荐使用此模块

profile。纯Python模块,存在明显开销,但想对其扩展的话相对照较easy

hotshot,实验性的C模块。主要关注开销最小化,现已不再被维护将来可能从Python移除

profile和cProfile接口同样。cProfile相对较新可能在某些平台上不可用



以cProfile为例来说明Python脚本性能剖析方法

*以命令行方式使用:

$ python -m cProfile [-o output_file] [-s sort_order] myscript.py

比如:

$ python -m cProfile -o myscript.out myscript.py

之后使用pstats对结果进行格式化:

$ python -c "import pstats; p=pstats.Stats('myscript.out'); p.print_stats()"

能够在格式化时指定排序字段:

$ python -c "import pstats; p=pstats.Stats('myscript.out'); p.sort_stats('time').print_stats()"

*直接在脚本内部使用:

import cProfile

import re

cProfile.run('re.compile("foo|bar")', 'restats')

import pstats

p = pstats.Stats('restats')

#strip_dirs()移除模块名之前的路径信息,sort_stats(-1)按标准名(module/line/name)排序,print_stats打印统计信息

p.strip_dirs().sort_stats(-1).print_stats()

#按time排序并显示前10行

p.sort_stats('time').print_stats(10)

#按file排序仅仅显示class init方法相关的统计信息

p.sort_stats('file').print_stats('__init__')

#先按time排序再按cum排序,仅仅输出50%。然后仅列出包括init的部分

p.sort_stats('time', 'cum').print_stats(.5, 'init')

#若想知道谁调用了上述函数能够使用

p.print_callers(.5, 'init')



*cProfile模块说明

函数:

cProfile.run(command, filename=None, sort=-1)

cProfile.runctx(command, globals, locals, filename=None)¶

类:

cProfile.Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True)

cProfile.Profile类下的方法:

enable()

Start collecting profiling data.



disable()

Stop collecting profiling data.



create_stats()

Stop collecting profiling data and record the results internally as the current profile.



print_stats(sort=-1)

Create a Stats object based on the current profile and print the results to stdout.



dump_stats(filename)

Write the results of the current profile to filename.



run(cmd)

Profile the cmd via exec().



runctx(cmd, globals, locals)

Profile the cmd via exec() with the specified global and local environment.



runcall(func, *args, **kwargs)

Profile func(*args, **kwargs)



*Stats类(pstats.Stats)说明

strip_dirs()    用以除去文件名称前的路径信息。

add(filename,[…]) 把profile的输出文件增加Stats实例中统计

dump_stats(filename) 把Stats的统计结果保存到文件

sort_stats(key,[…]) 最重要的一个函数,用以排序profile的输出

reverse_order() 把Stats实例里的数据反序重排

print_stats([restriction,…]) 把Stats报表输出到stdout

print_callers([restriction,…]) 输出调用了指定的函数的函数的相关信息

print_callees([restriction,…]) 输出指定的函数调用过的函数的相关信息

sort_stats支持下面參数:

參数
含义

'calls' call count

'cumulative' cumulative time

'cumtime' cumulative time

'file' file name

'filename' file name

'module' file name

'ncalls' call count

'pcalls' primitive call count

'line' line number

'name' function name

'nfl' name/file/line

'stdname' standard name

'time' internal time

'tottime' internal time

*一个比較典型的输出结果:

197 function calls (192 primitive calls) in 0.002 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)

     1    0.000    0.000    0.001    0.001 <string>:1(<module>)

     1    0.000    0.000    0.001    0.001 re.py:212(compile)

     1    0.000    0.000    0.001    0.001 re.py:268(_compile)

     1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)

     1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)

     4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)

   3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

输出结果说明:

共同拥有197次函数调用,原始调用为192次,原始调用说明不包括递归调用。

以standard name进行排序。

3/1表示发生了递归调用,1为原始调用次数,3为递归调用次数

ncalls 函数的被调用次数

tottime 函数总计执行时间。除去函数中调用的函数执行时间

percall 函数执行一次的平均时间,等于tottime/ncalls

cumtime 函数总计执行时间。含调用的函数执行时间

percall 函数执行一次的平均时间。等于cumtime/ncalls

filename:lineno(function) 函数所在的文件名称,函数的行号。函数名





參考:

https://docs.python.org/2/library/profile.html

Python脚本性能剖析的更多相关文章

  1. Python脚本性能分析

    来自:http://www.cnblogs.com/btchenguang/archive/2012/02/03/2337112.html def foo(): sum = 0 for i in ra ...

  2. [转] Python 代码性能优化技巧

    选择了脚本语言就要忍受其速度,这句话在某种程度上说明了 python 作为脚本的一个不足之处,那就是执行效率和性能不够理想,特别是在 performance 较差的机器上,因此有必要进行一定的代码优化 ...

  3. Python代码性能优化技巧

    摘要:代码优化能够让程序运行更快,可以提高程序的执行效率等,对于一名软件开发人员来说,如何优化代码,从哪里入手进行优化?这些都是他们十分关心的问题.本文着重讲了如何优化Python代码,看完一定会让你 ...

  4. Python 代码性能优化技巧(转)

    原文:Python 代码性能优化技巧 Python 代码优化常见技巧 代码优化能够让程序运行更快,它是在不改变程序运行结果的情况下使得程序的运行效率更高,根据 80/20 原则,实现程序的重构.优化. ...

  5. Python 代码性能优化技巧

    选择了脚本语言就要忍受其速度,这句话在某种程度上说明了 python 作为脚本的一个不足之处,那就是执行效率和性能不够理想,特别是在 performance 较差的机器上,因此有必要进行一定的代码优化 ...

  6. 基于binlog来分析mysql的行记录修改情况(python脚本分析)

          最近写完mysql flashback,突然发现还有有这种使用场景:有些情况下,可能会统计在某个时间段内,MySQL修改了多少数据量?发生了多少事务?主要是哪些表格发生变动?变动的数量是怎 ...

  7. 如何在python脚本开发做code review

    在软件项目开发中,我们经常提到一个词“code review”.code review中文翻译过来就是代码评审或复查,简而言之就是编码完成后由其他人通过阅读代码来检查代码的质量(可编译.可运行.可读. ...

  8. PyInstaller把Python脚本打包成可执行程序教程

    一.说明 一直以来都有把.py文件打包成.exe文件的想法,但总是不够强烈,每次拖着拖着就淡忘了. 昨天帮硬件部门的同事写了个脚本,然后今天下午的时候,他问有没有办法把脚本打包成可执行文件,这样方便以 ...

  9. MySQL 服务器性能剖析

    这是<高性能 MySQL(第三版)>第三章的读书笔记. 关于服务,常见的问题有: 如何确认服务器是否发挥了最大性能 找出执行慢的语句,为何执行慢 为何在用户端发生间歇性的停顿.卡死 通过性 ...

随机推荐

  1. centos7下配置samba,win10访问

    yum install -y samba samba-client 更改配置 [root@abcd mnt]# cat /etc/samba/smb.conf [global] workgroup = ...

  2. 【枚举】Codeforces Round #394 (Div. 2) C. Dasha and Password

    纪念死去的智商(虽然本来就没有吧……) 三重循环枚举将哪三个fix string作为数字.字母和符号位.记下最小的值就行了. 预处理之后这个做法应该是O(n^3)的,当然完全足够.不预处理是O(n^3 ...

  3. 【后缀数组】【线段树】poj3974 Palindrome

    考虑奇数长度的回文,对于字符串上的每个位置i,如果知道从i开始的后缀和到i为止的前缀反转后的字符串的lcp长度的话,也就知道了以第i个字符为对称中心的最长回文的长度了.因此,我们用在S中不会出现的字符 ...

  4. jquery区分苹果浏览器和安卓浏览器

    var browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; return { ...

  5. 【SQL Server】sql server更改了数据表的字段/新增数据表的字段 无法保存

    sql server更改了数据表的字段/新增数据表的字段  无法保存 解决方法:进入 工具-->选项-->Designers-->表设计器和数据库设计器-->取消勾选   即可

  6. pdf.js 添加自定义loading动画

    最近做了个手机端pdf预览的功能,用到pdf.js这个库,效果还不错.但是在网络差.文件大时,页面一直空白,体验不是很好. 于是加了个loading动画. <div id="loadi ...

  7. windows SFC(System File Checker) 命令的使用

    SFC(System File Checker)可以扫描所有受保护的系统文件的完整性,并使用正确的 Microsoft 版本替换. 步骤:点击开始,输入cmd: 右键,以管理员身份运行 输入sfc/s ...

  8. mysql 初始化报错 /usr/local/mysql/bin/mysqld:error while loading shared libraries :libaio.so.1

    安装mysql在初始化的时候,出现/usr/local/mysql/bin/mysqld:error while loading shared libraries:libaio.so.1 :canno ...

  9. (如何理解gamma校准)GAMMA测试方法及分析

    http://wenku.baidu.com/link?url=Wz5oXJsFQ-TVe3qxm9Zd4pp207cQ4jmjuBnwmWAvD1ibgoI2U8y7KCFhaR9xWtu9cGLE ...

  10. min-height IE6的解决方案

    selector { min-height:500px; height:auto !important; height:500px; } 因为IE6中当内容大于容器高度或宽度时,就会撑破容器.并且在同 ...