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)