PYTHON cProfile

Python性能监控之:cProfile

    Python内置监控模块cProfile可以监控程序内耗,对性能分析很有帮助。相关的还有profile、pstats、timeit和hotshot,cProfile可以检测到中断并保存数据。如下test.py:

times = 1000000
def foo():
    sum = 0
    for i in range(10):
        sum += 1
    sum = 0

def useFoo():
    foo()

def app1():
    global times
    for i in range(times):
        foo()

def app2():
    global times
    for i in range(times):
        useFoo()

app1()
app2()

执行:python -m cProfile -s time test.py 结果如下:

    5000008 function calls in 26.522 CPU seconds

    Ordered by: internal time

    ncalls   tottime   percall   cumtime   percall filename:lineno(function)

   2000000    11.705     0.000    16.949     0.000 test.py:2(foo)

   2000002     5.306      0.000     5.306      0.000 {range}

   1000000     4.796      0.000    14.812     0.000 test.py:8(useFoo)

         1     2.732     2.732    17.566   17.566 test.py:17(app2)

         1     1.982     1.982     8.954    8.954 test.py:12(app1)

         1     0.001     0.001    26.522    26.522 {execfile}

         1     0.000     0.000    26.520    26.520 test.py:1(<module>)

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

         1     0.000     0.000     0.000     0.000 {method 'disable' of '_lsprof.Profiler' objects}

.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32


    示例代码执行了两个函数,其中一个只是调用另一个。结果除了反应出程序各模块的耗时之外,也反应出Python函数调用的耗时:本示例中函数调用耗时多了一倍。

    另外有一个带GUI的工具VisualPyTune (vpt) ,支持profile、cProfile、hotspot和timeit,小试了一下截个图:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值