2020年11月6日 / 85次阅读 / Last Modified 2020年11月6日
分析python代码的运行时间,用python标准库中的模块,可以用timeit。不过,timeit主要用于一小段代码在反复运行后的平均时间分析,如果是对一个.py文件整体的运行分析,也不要反复运行,需要使用profile或者cProfile模块。
关于timeit:
timeit模块接口
在命令行使用python的timeit模块
cProfile,就是用C写的profile,两个都在python标准库中自带,我们一般使用cProfile,因为它更快一点,两个模块的使用和输出完全一样。
$ python3 -m cProfile read1.py
16777216
14350 function calls in 0.013 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 _bootlocale.py:33(getpreferredencoding)
1 0.000 0.000 0.000 0.000 codecs.py:260(__init__)
1 0.000 0.000 0.000 0.000 codecs.py:309(__init__)
2049 0.001 0.000 0.002 0.000 codecs.py:319(decode)
2049 0.000 0.000 0.000 0.000 codecs.py:331(getstate)
1 0.001 0.001 0.013 0.013 read1.py:1()
4097 0.008 0.000 0.011 0.000 read1.py:4(read_file)
2049 0.002 0.000 0.002 0.000 {built-in method _codecs.utf_8_decode}
1 0.000 0.000 0.000 0.000 {built-in method _locale.nl_langinfo}
1 0.000 0.000 0.013 0.013 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {built-in method builtins.iter}
4096 0.000 0.000 0.000 0.000 {built-in method builtins.len}
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
1 0.000 0.000 0.000 0.000 {built-in method io.open}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
可以看到输出默认的排序是 standard name,可以在命令行用 -s 参数指定用那个列来排序!
$ python3 -m cProfile -s tottime read2.py
将结果保存到某个指定的文件中,使用 -o 参数。 -h 参数 help。
有一些第三方的模块,可以将profile的结果以图形的方式展现出来。
在 python shell 中也可以使用profile:
>>> import cProfle
>>> cProfile.run(...)
对代码中的某一部分使用profile:
import cProfile
p = cProfile.Profile()
p.enable() #开始采集
...
...
p.disable() #结束采集
p.print_stats(sort='tottime') #打印结果
-- EOF --
本文链接:https://www.pynote.net/archives/2745
《profile模块的使用》有1条留言
©Copyright 麦新杰 Since 2019 Python笔记
性能问题符合20/80规则,即20%的代码引起了80%的性能损耗。为了快速定位瓶颈代码,推荐通过Profile来分析,能到达事半功倍的效果。 [ ]