可以使用 -m 标志运行多个模块吗?
我想对我的Python代码进行性能分析,尽可能多地获取一些参数信息:
1. 时间(目前使用的是 memory_profiler)
2. 内存(目前使用的是 cProfile 或 profile)
3. 输入/输出 - 每秒读取/写入的字节数(我还没找到相关的工具)
根据我的理解,最简单的方法是使用上面模块的 -m 标志(比如 python -m cProfile [-o output_file] [-s sort_order] myscript.py)
那么,我该如何同时对 memory_profiler 和 cProfile/profile 模块使用 -m 标志呢?
1 个回答
1
我觉得你不能用 -m 这个选项同时运行多个模块。不过,在你的脚本中使用 cProfile 其实很简单:
import cProfile, pstats
profiler = cProfile.Profile() # create profiler
profiler.enable() # start profiling
# do stuff
profiler.disable() # end profiling
with open('profile.txt', 'w') as fo: # open a file to print the stats
pstat_profile = pstats.Stats(profiler, stream=fo) # create a pstats object from the profile bound to a file stream
pstat_profile = print_stats() # print stats to a file
这样做会给你一个整齐的时间统计输出。现在你可以用 -m 选项运行这个修改过的脚本,配合 memory_profiler,这样就能同时获得两者的信息。
我不知道有没有基于 Python 的工具可以用来监控访问。不过,如果你在谷歌上搜索“测量 IO 速度”,会找到很多相关的信息,所以你应该能找到一些第三方工具(或者一些内置工具,比如如果你在 Linux 上可以用 DD)来跟踪 IO 性能,当你启动脚本时就可以使用。
最后,你会在一个 IO 日志器下运行一个有时间分析的脚本,同时使用内存分析工具,但我觉得它们应该能很好地配合在一起,而且它们之间的互动也很容易发现。例如,你在脚本中启动时间分析器时,会在内存分析中显示为内存分配,但你可以放心地忽略这些。