爱上python系列------python性能(三):KCacheGrind性能分析可视化

KCacheGrind是 一个性能可视化的工具,需要读取固定格式的文件就可以获取可视化的图形,不是属于python独有的

前面我们使用cProfile进行了性能分析,接下来我们使用cProfile分析后 ,然后保留成文件,该文件并不能直接被KCacheGrind
读取,需要使用工具pyprof2calltree进行转换,得到的文件是KCacheGrind可以使用的,然后就能得到可视化结果。
因此,接下来需要准备两个工具:
(1)KCacheGrind

这个直接可以下载:https://sourceforge.net/projects/qcachegrindwin/

因为KCacheGrind有很多个版本,为了方便查看结果(因为我的linux上面没有桌面),我使用的win版,下载后解压后就可以使用,无需安装。

(2)pyprof2calltree

安装很简单

root@root:/opt/pypy3.7-v7.3.2-linux64# pip3 install pyprof2calltree
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting pyprof2calltree
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/ca/2a/e9a76261183b4b5e059a6625d7aae0bcb0a77622bc767d4497148ce2e218/pyprof2calltree-1.4.5.tar.gz
Building wheels for collected packages: pyprof2calltree
  Running setup.py bdist_wheel for pyprof2calltree ... done
  Stored in directory: /root/.cache/pip/wheels/1f/d5/22/e302f7ad85b7bef4f591f7e9b75c681ceea602400bacd9fcdc
Successfully built pyprof2calltree
Installing collected packages: pyprof2calltree
Successfully installed pyprof2calltree-1.4.5

接下来就进行整个流程了:

(一)获取.prof文件

import cProfile
import pstats
import sys

def run(): 
    a = [1]*100 
    b = [x**3 for x in a ] 
    c = [x for x in b] 
    d = c*2 

profiler = cProfile.Profile()
profiler.enable()##start                     
run()
profiler.create_stats()
stats = pstats.Stats(profiler)
stats.strip_dirs().sort_stats('cumulative').dump_stats('run.prof')#保存为run.prof

(二)转换为KCacheGrind可读取的文件

上面 运行成功后得到一个名为run.prof的 文件

接下需要转换:

pyprof2calltree -i run.prof

参数解释:

root@root:/opt/pypy3.7-v7.3.2-linux64# pyprof2calltree -h
usage: pyprof2calltree [-h] [-o output_file_path] [-i input_file_path] [-k]
                       [-r ...]

optional arguments:
  -h, --help            show this help message and exit
  -o output_file_path, --outfile output_file_path
                        Save calltree stats to <outfile>
  -i input_file_path, --infile input_file_path
                        Read Python stats from <infile>
  -k, --kcachegrind     Run the kcachegrind tool on the converted data
  -r ..., --run-script ...
                        Name of the Python script to run to collect profiling
                        data

上面的命令没有使用-o,也就是没有 指定名字,会生成一个run.prof.log文件

这个可以使用指定的:

-o 名称

而且如果本机安装了KCacheGrind,可以使用-k这个参数,也就是会自动打开KCacheGrind

不过我是将run.prof.log文件拷贝到了win上面,然后进行读取的:

最后附上KCacheGrind指导书:https://docs.kde.org/trunk5/en/kdesdk/kcachegrind/kcachegrind.pdf

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/109185386
今日推荐