代码:

(1)

import cProfile
import re
cProfile.run('re.compile("foo|bar")')
  • 1.
  • 2.
  • 3.


运行结果:

python性能分析器:cProfile_python



(2)

import cProfile
def runRe():
    import re
    cProfile.runctx('re.compile("foo|bar")', None, locals())
runRe()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.


运行结果:

python性能分析器:cProfile_python_02



(3)

import cProfile

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

prof = cProfile.Profile() 
prof.enable() 
runRe()
prof.create_stats()
prof.print_stats()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.


运行结果:

python性能分析器:cProfile_python_03



(4)

# import cProfile

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

# prof = cProfile.Profile() 
# prof.enable() 
runRe()
# prof.create_stats()
# prof.print_stats()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.


运行结果:

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

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

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

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

python性能分析器:cProfile_python_04



(5)

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

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


运行结果:

python性能分析器:cProfile_python_05



(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()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.