2

我想用尽可能多的参数来分析我的 python 代码: 1. 时间(当前使用memory_profiler) 2. 内存(当前使用cProfile或使用profile) 3. I/O - 每秒读/写字节数(没有找到任何)

最简单的事情(据我所知)是在上面的模块上使用 -m 标志(例如python -m cProfile [-o output_file] [-s sort_order] myscript.py

那么,如何对 memory_profiler 和 cProfile/profile 模块使用 -m 标志?

4

1 回答 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 的工具来监控访问。但是,Google 搜索“测量 IO 速度”会在各处搜索到,因此您应该能够找到可以找到的第三方实用程序(或一些内置工具,如 DD,如果您在 Linux 上)用于在启动脚本时跟踪 IO 性能。

您最终将在 IO 记录器内的内存分析器下运行时间分析脚本,但我认为它们应该可以很好地协同工作,并且它们的交互应该很容易被发现。例如,您在脚本内启动时间分析器将在内存配置文件中显示为内存分配,但您会知道可以忽略它们。

于 2014-08-13T15:20:14.883 回答