You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller打包的exe程序如何通过cProfile命令行做性能分析

对PyInstaller打包的EXE程序进行cProfile性能分析

方法1:修改主脚本集成cProfile逻辑(需重新打包)

如果你的主脚本是myapp.py,可以在入口处添加性能分析触发逻辑,让打包后的EXE可通过参数开启分析:

  1. 修改myapp.py的入口代码:
    假设原入口是:
if __name__ == "__main__":
    main()

改成:

import cProfile
import sys

def main():
    # 原有的主程序逻辑
    pass

if __name__ == "__main__":
    if "--profile" in sys.argv:
        sys.argv.remove("--profile")
        profiler = cProfile.Profile()
        profiler.enable()
        main()
        profiler.disable()
        profiler.dump_stats("myapp_profile.stats")
        print(f"性能分析结果已保存至 myapp_profile.stats")
    else:
        main()
  1. 重新执行打包命令:
pyinstaller my.spec --dist mydir --noconfirm
  1. 运行带分析参数的EXE:
mydir/myapp --profile

执行完成后,当前目录会生成myapp_profile.stats分析文件。

方法2:修改spec文件指定cProfile为启动入口(需重新打包)

不想修改主脚本的话,可以直接修改my.spec,让PyInstaller以cProfile为入口运行你的主程序:

  1. 打开my.spec,找到EXE节点,添加argv参数指定cProfile的运行逻辑:
EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='myapp',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,  # GUI程序改为False
    # 指定cProfile作为入口,生成分析文件
    argv=['-m', 'cProfile', '-o', 'myapp_profile.stats', 'myapp.py']
)

注意:myapp.py需是主脚本的正确文件名,确保它在PyInstaller的搜索路径内。

  1. 重新打包:
pyinstaller my.spec --dist mydir --noconfirm
  1. 直接运行EXE即可自动生成分析文件:
mydir/myapp

查看pstats分析结果

生成.stats文件后,有两种常用方式查看分析数据:

方式1:命令行交互查看

在终端执行:

python -m pstats myapp_profile.stats

进入交互环境后,可使用这些常用命令:

  • sort cumulative:按累计运行时间排序
  • print 20:输出前20条结果
  • help:查看所有可用命令

方式2:脚本批量分析

编写简单脚本实现自定义分析:

import pstats

stats = pstats.Stats("myapp_profile.stats")
# 按累计时间排序,显示前20条核心调用
stats.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20)
# 也可按实际运行时间排序:stats.sort_stats(pstats.SortKey.TIME).print_stats()

运行脚本即可直接输出格式化的分析结果。


内容的提问来源于stack exchange,提问作者amu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:50:26