python性能分析器:cProfile

代码:

(1)

import cProfile
import re
cProfile.run('re.compile("foo|bar")')

运行结果:

image



(2)

import cProfile
def runRe():
    import re
    cProfile.runctx('re.compile("foo|bar")', None, locals())
runRe()

运行结果:

image



(3)

import cProfile

import re
def runRe():
    re.compile("foo|bar")

prof = cProfile.Profile() 
prof.enable() 
runRe()
prof.create_stats()
prof.print_stats()

运行结果:

image



(4)

# import cProfile

import re
def runRe():
    re.compile("foo|bar")

# prof = cProfile.Profile() 
# prof.enable() 
runRe()
# prof.create_stats()
# prof.print_stats()

运行结果:

python -m cProfile -o x.profile x.py

需要注意的是,如果写成:

python -m cProfile x.py -o x.profile

那么就不会生成x.profile文件。

image



(5)

对生成的性能文件x.profile进行内容解析和打印:

import pstats
p = pstats.Stats('x.profile')
p.strip_dirs().sort_stats(-1).print_stats()

运行结果:

image



(6)

import cProfile
import pstats

def runRe():
    import re
    re.compile("foo|bar")
prof = cProfile.Profile()
prof.enable()
runRe()
prof.create_stats()

p = pstats.Stats(prof)
p.print_callers()







posted on 2024-07-30 08:55  Angry_Panda  阅读(27)  评论(0编辑  收藏  举报

导航