Python是一種解釋性的語言,執行速度相比C、C++等語言比較緩慢;我們需要在其它地方上下功夫來提高代碼的執行速度,首先需要對代碼進行分析,這個時候則需要用一些性能測驗工具:

一、 Module time
time.time
最普通的手段就是時間之差,其它編程語言中也都會到過此方法:
>>> from time import time
>>> def fib(n):
if n<3:return 1
return fib(n-1)+fib(n-2)
>>> t = time(); fib(30); time()-t
832040
0.4218752384185791
>>> t = time(); fib(35); time()-t
9227465
4.656255722045898
>>> t = time(); fib(40); time()-t
102334155
51.281249046325684
>>>
斐波那契數列未改進的遞回是比較耗時的,就專門以它為例了,
除time()函式外,時間庫里可用來計時的函式有很多,還成對的(_ns后綴的以納秒為單位):
time.time()
time.time_ns()time.monotonic()
time.monotonic_ns()time.perf_counter()
time.perf_counter_ns()time.process_time()
time.process_time_ns()time.thread_time()
time.thread_time_ns()
區別一:
time 時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量
monotonic 表示的是從作業系統的啟動時間開始按秒計算的偏移量
perf_counter 表示的是從程式的啟動時間開始按秒計算的偏移量,如下面所舉的例子中,它的回傳值(613.323613)表示Python IDLE Shell視窗打開的時間,
如把perf_counter()放在源程式未尾結束處(比如放在陳述句_exit(0)前)就不用計算差值,回傳的時間就是程式從啟動到退出的時間,
>>> from time import time,monotonic,perf_counter
>>> time()
1633249386.5061808
>>> monotonic()
4594.25
>>> perf_counter()
613.323613
>>>
區別二:
處理行程、執行緒時間的不受sleep影響
>>> from time import time,sleep,process_time,thread_time
>>> def fib(n):
if n<3:return 1
return fib(n-1)+fib(n-2)
>>> t = time(); fib(30); time()-t
832040
0.432178258895874
>>> t = thread_time(); fib(30); thread_time()-t
832040
0.421875
>>> t = time(); sleep(1); fib(30); sleep(1); time()-t
832040
2.463411569595337
>>> t = process_time(); sleep(1); fib(30); sleep(1); process_time()-t
832040
0.421875
>>> t = thread_time(); sleep(1); fib(30); sleep(1); thread_time()-t
832040
0.4375
>>>
二、 Module timeit
比較適合測驗小段代碼:
>>> from timeit import timeit
>>> timeit(stmt='a=10;b=10;sum=a+b')
0.11455389999997578
>>> timeit(stmt='a=10;b=10;sum=a+b',number=10000)
0.0013638000000355532
>>>
程式中的使用如下:
import timeit
def fib(n):
if n<3:return 1
return fib(n-1)+fib(n-2)
if __name__ == '__main__':
tm = timeit.Timer('fib(40)', 'from __main__ import fib')
print(tm.timeit(1))
注意: .timeit() 的引數number默認值為1000000,上例中tm.timeit()不用引數的話停不了
這個模塊還能在DOS命令視窗下執行:
D:\>python -m timeit -n 30 -s "import random" "[random.random() for i in range(100000)]"
30 loops, best of 5: 23.1 msec per loop
三、 Module cProfile
這個模塊除了給出呼叫時間,還報告函式呼叫次數:
>>> from cProfile import Profile
>>> f = lambda n:1 if n<3 else f(n-1)+f(n-2)
>>> cp = Profile()
>>> cp.enable(); n = f(30); cp.disable()
>>> cp.print_stats()
1664081 function calls (3 primitive calls) in 1.007 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1664079/1 1.007 0.000 1.007 1.007 <pyshell#70>:1(<lambda>)
1 0.000 0.000 0.000 0.000 rpc.py:614(displayhook)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
>>> 2*f(30)-1
1664079
>>>
為什么f(30)的呼叫次數ncalls = 2*f(30)-1,因為我用傻辦法驗證過所以我知道,
這個模塊還能在DOS命令視窗下執行:
D:\>python -m cProfile -s cumulative test1.py
350 function calls (343 primitive calls) in 0.002 secondsOrdered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
3/1 0.000 0.000 0.002 0.002 {built-in method builtins.exec}
1 0.000 0.000 0.002 0.002 test1.py:1(<module>)
2/1 0.000 0.000 0.002 0.002 <frozen importlib._bootstrap>:986(_find_and_load)
2/1 0.000 0.000 0.002 0.002 <frozen importlib._bootstrap>:956(_find_and_load_unlocked)
2/1 0.000 0.000 0.001 0.001 <frozen importlib._bootstrap>:650(_load_unlocked)
2 0.000 0.000 0.001 0.000 <frozen importlib._bootstrap>:890(_find_spec)
1 0.000 0.000 0.001 0.001 <frozen importlib._bootstrap_external>:777(exec_module)
1 0.000 0.000 0.001 0.001 <frozen importlib._bootstrap_external>:1334(find_spec)
1 0.000 0.000 0.001 0.001 <frozen importlib._bootstrap_external>:1302(_get_spec)
4 0.000 0.000 0.001 0.000 <frozen importlib._bootstrap_external>:1431(find_spec)
6 0.000 0.000 0.001 0.000 <frozen importlib._bootstrap_external>:80(_path_stat)
6 0.001 0.000 0.001 0.000 {built-in method nt.stat}...........省略很多行..........
四、 Module line_profiler
運行時間逐行分析報告,測驗檔案test1.py原始碼如下:
@profile
def fib(n):
if n<3:return 1
return fib(n-1)+fib(n-2)
if __name__ == '__main__':
print(fib(30))
不用import匯入,只在測驗函式前加上裝飾器 @profile ,測驗在DOS視窗進行:
D:\>kernprof -l -v test1.py
832040
Wrote profile results to test1.py.lprof
Timer unit: 1e-06 sTotal time: 3.07291 s
File: test1.py
Function: fib at line 1Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 @profile
2 def fib(n):
3 1664079 1341610.0 0.8 43.7 if n<3:return 1
4 832039 1731304.5 2.1 56.3 return fib(n-1)+fib(n-2)
D:\>
五、Module memory_profiler
記憶體使用逐行分析報告,使用方法基本同上還是測驗test1.py,命令如下:
D:\>python -m memory_profiler test1.py
832040
Filename: test1.pyLine # Mem usage Increment Occurences Line Contents
============================================================
1 29.203 MiB -139766.219 MiB 1664079 @profile
2 def fib(n):
3 29.203 MiB -139795.418 MiB 1664079 if n<3:return 1
4 29.203 MiB -69899.141 MiB 832039 return fib(n-1)+fib(n-2)
六、Module guppy
查看物件占用的堆記憶體大小
此模塊安裝時碰到:
error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
需要VC++14,所以沒裝沒能親測,大致用法:
from guppy import hpy import gc hp = hpy() ast = parse_file('filename') gc.collect() h = hp.heap() print(h)
以上涉及的所有模塊,都可以在dos視窗下驗證有無或者在線安裝:
D:\>pip show xxModule
WARNING: Package(s) not found: xxModuleD:\>pip install xxModule
最后,說一下模塊這個英文單詞 module,我之前一直讀成 “媽逗”,大概受了單詞 model 的影響,今天我查了字典,才知道module應該讀作“媽舅” ^_^
你是怎么讀的呢? 讀對的請點贊!讀錯的請點收藏!!沒想過怎么讀的點一鍵三連!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/305210.html
標籤:python
