1. 程式人生 > >Python的7種性能測試工具:timeit、profile、cProfile、line_profiler、memory_profiler、PyCharm圖形化效能測試工具、objgraph

Python的7種性能測試工具:timeit、profile、cProfile、line_profiler、memory_profiler、PyCharm圖形化效能測試工具、objgraph

1.timeit:

>>> import timeit
>>> def fun():
    for i in range(100000):
        a = i * i

>>> timeit.timeit('fun()', 'from __main__ import fun', number=1)
0.02922706632834235
>>>  

timeit只輸出被測試程式碼的總執行時間,單位為秒,沒有詳細的統計。

2.profile

profile:純Python實現的效能測試模組,介面和cProfile一樣。

>>> import profile
>>> def fun():
   for i in range(100000):
      a = i * i

      

>>> profile.run('fun()')
         5 function calls in 0.031 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.016    0.016 :0(exec)
        1    0.016    0.016    0.016    0.016 :0(setprofile)
        1    0.016    0.016    0.016    0.016 <pyshell#13>:1(fun)
        1    0.000    0.000    0.016    0.016 <string>:1(<module>)
        1    0.000    0.000    0.031    0.031 profile:0(fun())
        0    0.000             0.000          profile:0(profiler)


>>> 

ncall:函式執行次數

tottime: 函式的總的執行時間,減去函式中呼叫子函式的執行時間

第一個percall:percall = tottime / nclall 

cumtime:函式及其所有子函式調整的執行時間,也就是函式開始呼叫到結束的時間。

第二個percall:percall = cumtime / nclall 

3.cProfile

profile:c語言實現的效能測試模組,介面和profile一樣。

>>> import cProfile
>>> def fun():
   for i in range(100000):
      a = i * i

      
>>> cProfile.run('fun()')
         4 function calls in 0.024 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.024    0.024    0.024    0.024 <pyshell#17>:1(fun)
        1    0.000    0.000    0.024    0.024 <string>:1(<module>)
        1    0.000    0.000    0.024    0.024 {built-in method exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


>>> 
ncalls、tottime、percall、cumtime含義同profile。

4.line_profiler

安裝:

pip install line_profiler

安裝之後kernprof.py會加到環境變數中。

line_profiler可以統計每行程式碼的執行次數和執行時間等,時間單位為微妙。

測試程式碼:

C:\Python34\test.py

import time


@profile
def fun():
    a = 0
b = 0
for i in range(100000):
        a = a + i * i

    for i in range(3):
        b += 1
time.sleep(0.1) return a + b fun()

使用:

1.在需要測試的函式加上@profile裝飾,這裡我們把測試程式碼寫在C:\Python34\test.py檔案上.

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

輸出結果如下:


Total Time:測試程式碼的總執行時間 
Hits:表示每行程式碼執行的次數  
Time:每行程式碼執行的總時間  
Per Hits:每行程式碼執行一次的時間  
% Time:每行程式碼執行時間的百分比

5.memory_profiler:

memory_profiler工具可以統計每行程式碼佔用的記憶體大小。  

安裝:

pip install memory_profiler  

pip install psutil  

測試程式碼:  

同line_profiler。 

使用: 

1.在需要測試的函式加上@profile裝飾
  
2.執行命令: python -m memory_profiler C:\Python34\test.py 
  
輸出如下:

6.PyCharm圖形化效能測試工具:

7.objgraph:

objgraph是一個實用模組,可以列出當前記憶體中存在的物件,可用於定位記憶體洩露。

objgraph需要安裝:

pip install objgraph

使用方法這裡不做描述,自行百度。