1. >>> import timeit
  2. >>> def fun():
  3. for i in range(100000):
  4. a = i * i
  5.  
  6. >>> timeit.timeit(\'fun()\', \'from __main__ import fun\', number=1)
  7. 0.02922706632834235
  8. >>>

 

 

timeit只输出被测试代码的总运行时间,单位为秒,没有详细的统计。

 

profile:纯Python实现的性能测试模块,接口和cProfile一样。

 

  1. >>> import profile
  2. >>> def fun():
  3. for i in range(100000):
  4. a = i * i
  5.  
  6.  
  7. >>> profile.run(\'fun()\')
  8. 5 function calls in 0.031 seconds
  9.  
  10. Ordered by: standard name
  11.  
  12. ncalls tottime percall cumtime percall filename:lineno(function)
  13. 1 0.000 0.000 0.016 0.016 :0(exec)
  14. 1 0.016 0.016 0.016 0.016 :0(setprofile)
  15. 1 0.016 0.016 0.016 0.016 <pyshell#13>:1(fun)
  16. 1 0.000 0.000 0.016 0.016 <string>:1(<module>)
  17. 1 0.000 0.000 0.031 0.031 profile:0(fun())
  18. 0 0.000 0.000 profile:0(profiler)
  19.  
  20.  
  21. >>>

 

 

ncall:函数运行次数

tottime: 函数的总的运行时间,减去函数中调用子函数的运行时间

第一个percall:percall = tottime / nclall 

cumtime:函数及其所有子函数调整的运行时间,也就是函数开始调用到结束的时间。

第二个percall:percall = cumtime / nclall 

 

profile:c语言实现的性能测试模块,接口和profile一样。

 

  1. >>> import cProfile
  2. >>> def fun():
  3. for i in range(100000):
  4. a = i * i
  5.  
  6. >>> cProfile.run(\'fun()\')
  7. 4 function calls in 0.024 seconds
  8.  
  9. Ordered by: standard name
  10.  
  11. ncalls tottime percall cumtime percall filename:lineno(function)
  12. 1 0.024 0.024 0.024 0.024 <pyshell#17>:1(fun)
  13. 1 0.000 0.000 0.024 0.024 <string>:1(<module>)
  14. 1 0.000 0.000 0.024 0.024 {built-in method exec}
  15. 1 0.000 0.000 0.000 0.000 {method \'disable\' of \'_lsprof.Profiler\' objects}
  16.  
  17.  
  18. >>>

ncalls、tottime、percall、cumtime含义同profile。

 

 

pip install line_profiler

安装之后kernprof.py会加到环境变量中。

line_profiler可以统计每行代码的执行次数和执行时间等,时间单位为微妙。

C:\Python34\test.py

  1.  
  1. import time
  2.  
  3.  
  4. @profile
  5. def fun():
  6. a = 0
  7. b = 0
  8. for i in range(100000):
  9. a = a + i * i
  10.  
  11. for i in range(3):
  12. b += 1
  13. time.sleep(0.1)
  14.  
  15. return a + b
  16.  
  17.  
  18. fun()

1.在需要测试的函数加上@profile装饰,这里我们把测试代码写在C:\Python34\test.py文件上.

2.运行命令行:kernprof -l -v C:\Python34\test.py

输出结果如下:

Total Time:测试代码的总运行时间 
Hits:表示每行代码运行的次数  
Time:每行代码运行的总时间  
Per Hits:每行代码运行一次的时间  
% Time:每行代码运行时间的百分比

 

memory_profiler工具可以统计每行代码占用的内存大小。  

pip install memory_profiler  

pip install psutil  

同line_profiler。 

1.在需要测试的函数加上@profile装饰
  
2.执行命令: python -m memory_profiler C:\Python34\test.py 
  
输出如下:

 

PyCharm提供了图像化的性能分析工具,使用方法见利用PyCharm的Profile工具进行Python性能分析

 

objgraph是一个实用模块,可以列出当前内存中存在的对象,可用于定位内存泄露。

objgraph需要安装:

 

  1. pip install objgraph

 

 

使用方法这里不做描述,自行百度。

版权声明:本文为yaoyao9446原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/yaoyao9446/p/9242077.html