python性能监控工具_Python性能监控

profiler是一个程序,用来描述运行时的程序性能,并且从不同方面提供统计数据加以表述。Python中含有3个模块提供这样的功能,分别是cProfile, profile和pstats。这些分析器提供的是对Python程序的确定性分析。同时也提供一系列的报表生成工具,允许用户快速地检查分析结果。

Python标准库提供了3个不同的性能分析器:

cProfile,推荐给大部分的用户,是C的一个扩展应用,因为其合理的运行开销,所以适合分析运行时间较长的。是基于lsprof。

profile,一个纯python模块,它的接口和cProfile一致。在分析程序时,增加了很大的运行开销。如果你想扩展profiler的功能,可以试着继承这个模块

hotshot, 一个试验性的c模块,关注减少分析时的运行开销,但是是以需要更长的数据后处理的次数为代价。不过这个模块不再被维护,也有可能在新的python版本中被弃用。

比如在flask,可以这样使用

from app import app

if __name__ == '__main__':

app.debug = True

import cProfile

cProfile.run("app.run(host='127.0.0.1', port=80)", "c:\\wwww123.txt")

import pstats

p = pstats.Stats("c:\\wwww123.txt")

p.sort_stats("time").print_stats(20)

#app.run(host="127.0.0.1", port=80)

if __name__== "__main__":

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python程序的内存使用情况可以使用Python内置的`memory_profiler`模块进行监视。`memory_profiler`可以帮助我们分析Python程序的内存使用情况,找出内存泄漏等问题。 安装`memory_profiler`模块: ```python pip install memory_profiler ``` 使用`memory_profiler`监视Python程序的内存使用情况: 1. 在需要监视的函数上添加`@profile`装饰器。 2. 运行程序时加上`-m memory_profiler`参数,并指定要监视的文件名。 例如,我们有以下Python程序: ```python from random import randint @profile def generate_list(): nums = [randint(0, 100) for _ in range(1000000)] return nums if __name__ == '__main__': nums = generate_list() print(sum(nums)) ``` 我们可以在`generate_list()`函数上加上`@profile`装饰器,然后运行以下命令: ```python python -m memory_profiler memory_test.py ``` 输出结果: ``` Filename: memory_test.py Line # Mem usage Increment Line Contents ================================================ 3 52.5 MiB 52.5 MiB @profile 4 def generate_list(): 5 81.9 MiB 29.4 MiB nums = [randint(0, 100) for _ in range(1000000)] 6 81.9 MiB 0.0 MiB return nums 12671490 ``` 输出结果中,`Line #`表示代码行号,`Mem usage`表示该行执行后的内存使用情况,`Increment`表示相对于上一行的内存增加量,`Line Contents`表示该行代码内容。我们可以看到,在`generate_list()`函数中,内存使用量从52.5 MiB增加到81.9 MiB,增加了29.4 MiB,随着程序的执行结束,内存使用量又降回到了52.5 MiB。 通过`memory_profiler`模块的输出结果,我们可以找出Python程序中的内存泄漏和不必要的内存占用,从而进行优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值