如果希望对程序进行优化,那么性能分析是必不可少的。标准库中包含了一个叫profile的模块,使用起来非常简单
import profile, my_math profile.run('my_math.square(100)')只需要运行该模块的run方法,(需要注意的是参数为字符串。)即可得到如下结果:
4 function calls in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.001 0.001 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 my_math.py:3(square)
1 0.000 0.000 0.001 0.001 profile:0(my_math.square(100))
0 0.000 0.000 profile:0(profiler)
其中my_math.py中内容为
def square(x): return x**2
Process finished with exit code 0