Python的性能分析工具cProfile使用起来比较简单,如下:
python -m cProfile -o profile.txt xxx.py arg1 arg2 ...
其中,xxx.py
是要分析的python程序入口函数,后面跟的就是对应的参数了。
生成的profile.txt
是存储的profile信息,可以用下面的python脚本查询。
check_profile.py
的内容如下:
#coding:utf-8
import pstats
import sys
p=pstats.Stats(sys.argv[1])
p.sort_stats('cumulative').print_stats()
用法很简单:
$ python3 check_profile.py profile.txt
然后,就可以看到下面的类似的信息了:
Fri Sep 20 13:37:54 2019 profile.txt
14927559 function calls (14919846 primitive calls) in 26.559 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
410/1 0.004 0.000 26.559 26.559 {built-in method builtins.exec}
1 0.000 0.000 26.559 26.559 generate_glasses.py:2(<module>)
1 0.000 0.000 24.723 24.723 generate_glasses.py:35(main)
1 0.000 0.000 24.465 24.465 /usr/local/lib/python3.7/site-packages/psopy/minimize.py:216(minimize)
1 0.000 0.000 24.463 24.463 /usr/local/lib/python3.7/site-packages/psopy/minimize.py:44(_minimize_pso)
1 0.000 0.000 24.451 24.451 /usr/local/lib/python3.7/site-packages/psopy/minimize.py:433(<lambda>)
1 0.002 0.002 24.451 24.451 /usr/local/lib/python3.7/site-packages/numpy/lib/shape_base.py:23(apply_along_axis)
78 0.008 0.000 24.448 0.313 generate_glasses.py:15(compare_generated_face_with_target)
78 0.001 0.000 17.289 0.222 /usr/local/lib/python3.7/site-packages/face_recognition/api.py:190(face_encodings)
78 0.002 0.000 15.405 0.198 /usr/local/lib/python3.7/site-packages/face_recognition/api.py:151(_raw_face_landmarks)
78 15.280 0.196 15.280 0.196 /usr/local/lib/python3.7/site-packages/face_recognition/api.py:89(_raw_face_locations)