Python代碼性能優化技巧

來自:IBM developWorks

Python代碼性能優化技巧

摘要:代碼優化能夠讓程序運行更快,可以提高程序的執行效率等,對於一名軟件開發人員來說,如何優化代碼,從哪裏入手進行優化?這些都是他們十分關心的問題。本文着重講了如何優化Python代碼,看完一定會讓你收穫滿滿!

代碼優化能夠讓程序運行更快,它是在不改變程序運行結果的情況下使得程序的運行效率更高,根據80/20原則,實現程序的重構、優化、擴展以及文檔相關的事情通常需要消耗80%的工作量。優化通常包含兩方面的內容:減小代碼的體積,提高代碼的運行效率。

改進算法,選擇合適的數據結構

一個良好的算法能夠對性能起到關鍵作用,因此性能改進的首要點是對算法的改進。在算法的時間複雜度排序上依次是:

O(1) -> O(lg n) -> O(n lg n) -> O(n^2) -> O(n^3) -> O(n^k) -> O(k^n) -> O(n!)

因此如果能夠在時間複雜度上對算法進行一定的改進,對性能的提高不言而喻。但對具體算法的改進不屬於本文討論的範圍,讀者可以自行參考這方面資料。下面的內容將集中討論數據結構的選擇。

  • 字典(dictionary)與列表(list)

Python字典中使用了hash table,因此查找操作的複雜度爲O(1),而list實際是個數組,在list中,查找需要遍歷整個list,其複雜度爲O(n),因此對成員的查找訪問等操作字典要比list更快。

清單1.代碼dict.py

  1. from time import time  
  2.  t = time()  
  3.  list = ['a','b','is','python','jason','hello','hill','with','phone','test',  
  4.  'dfdf','apple','pddf','ind','basic','none','baecr','var','bana','dd','wrd']  
  5.  #list = dict.fromkeys(list,True)  
  6.  print list  
  7.  filter = []  
  8.  for i in range (1000000):  
  9.  for find in ['is','hat','new','list','old','.']:  
  10.  if find not in list:  
  11.  filter.append(find)  
  12.  print "total run time:"  
  13.  print time()-t 

上述代碼運行大概需要16.09seconds。如果去掉行#list=dict.fromkeys(list,True)的註釋,將list轉換爲字典之後再運行,時間大約爲8.375 seconds,效率大概提高了一半。因此在需要多數據成員進行頻繁的查找或者訪問的時候,使用dict而不是list是一個較好的選擇。

  • 集合(set)與列表(list)

set的union,intersection,difference操作要比list的迭代要快。因此如果涉及到求list交集,並集或者差的問題可以轉換爲set來操作。

清單2.求list的交集:

  1. from time import time  
  2.  t = time()  
  3.  lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44]  
  4.  listb=[2,4,6,9,23]  
  5.  intersection=[]  
  6.  for i in range (1000000):  
  7.  for a in lista:  
  8.  for b in listb:  
  9.  if a == b:  
  10.  intersection.append(a)  
  11. print "total run time:"  
  12.  print time()-t 

上述程序的運行時間大概爲:

total run time:

38.4070000648

清單3. 使用set求交集

  1. from time import time  
  2.  t = time()  
  3.  lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44]  
  4.  listb=[2,4,6,9,23]  
  5.  intersection=[]  
  6.  for i in range (1000000):  
  7.  list(set(lista)&set(listb))  
  8.  print "total run time:"  
  9.  print time()-t 

改爲set後程序的運行時間縮減爲8.75,提高了4倍多,運行時間大大縮短。讀者可以自行使用表1其他的操作進行測試。

表1.set常見用法

語法                      操作                    說明

set(list1)|set(list2)  union        包含list1和list2所有數據的新集合

set(list1)&set(list2) intersection  包含list1和list2中共同元素的新集合

set(list1)–set(list2) difference   在list1中出現但不在list2中出現的元素的集合

對循環的優化

對循環的優化所遵循的原則是儘量減少循環過程中的計算量,有多重循環的儘量將內層的計算提到上一層。 下面通過實例來對比循環優化後所帶來的性能的提高。程序清單4中,如果不進行循環優化,其大概的運行時間約爲132.375。

清單4.爲進行循環優化前

  1. from time import time  
  2.  t = time()  
  3.  lista = [1,2,3,4,5,6,7,8,9,10]  
  4.  listb =[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.01]  
  5.  for i in range (1000000):  
  6.  for a in range(len(lista)):  
  7.  for b in range(len(listb)):  
  8.  x=lista[a]+listb[b]  
  9.  print "total run time:"  
  10.  print time()-t 

現在進行如下優化,將長度計算提到循環外,range用xrange代替,同時將第三層的計算lista[a]提到循環的第二層。

清單5.循環優化後

  1. from time import time  
  2.  t = time()  
  3.  lista = [1,2,3,4,5,6,7,8,9,10]  
  4.  listb =[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.01]  
  5.  lenlen1=len(lista)  
  6.  lenlen2=len(listb)  
  7.  for i in xrange (1000000):  
  8.  for a in xrange(len1):  
  9.  temp=lista[a]  
  10.  for b in xrange(len2):  
  11.  x=temp+listb[b]  
  12.  print "total run time:"  
  13.  print time()-t 

上述優化後的程序其運行時間縮短爲102.171999931。在清單4中lista[a] 被計算的次數爲1000000*10*10,而在優化後的代碼中被計算的次數爲1000000*10,計算次數大幅度縮短,因此性能有所提升。

充分利用Lazy if-evaluation的特性

Python中條件表達式是lazy evaluation的,也就是說如果存在條件表達式if x and y,在x爲false的情況下y表達式的值將不再計算。因此可以利用該特性在一定程度上提高程序效率。

清單6.利用Lazy if-evaluation的特性

  1. from time import time  
  2.  t = time()  
  3.  abbreviations = ['cf.', 'e.g.', 'ex.', 'etc.', 'fig.', 'i.e.', 'Mr.', 'vs.']  
  4.  for i in range (1000000):  
  5.  for w in ('Mr.', 'Hat', 'is', 'chasing', 'the', 'black', 'cat', '.'):  
  6.  if w in abbreviations:  
  7.  #if w[-1] == '.' and w in abbreviations:  
  8.  pass  
  9.  print "total run time:"  
  10.  print time()-t 

在未進行優化之前程序的運行時間大概爲8.84,如果使用註釋行代替第一個if,運行的時間大概爲6.17。

字符串的優化

Python中的字符串對象是不可改變的,因此對任何字符串的操作如拼接,修改等都將產生一個新的字符串對象,而不是基於原字符串,因此這種持續的copy會在一定程度上影響Python的性能。對字符串的優化也是改善性能的一個重要的方面,特別是在處理文本較多的情況下。字符串的優化主要集中在以下幾個方面:

1、在字符串連接的使用盡量使用join()而不是+:在代碼清單7中使用+進行字符串連接大概需要0.125s,而使用join縮短爲0.016s。因此在字符的操作上join比+要快,因此要儘量使用join而不是+。

清單7.使用join而不是+連接字符串

  1. from time import time  
  2. t = time()  
  3.  s = "" 
  4.  list = ['a','b','b','d','e','f','g','h','i','j','k','l','m','n']  
  5.  for i in range (10000):  
  6.  for substr in list:  
  7.  s+= substr  
  8.  print "total run time:"  
  9.  print time()-t 

同時要避免:

  1. s = "" 
  2.  for x in list:  
  3.  s += func(x) 

而是要使用:

  1. slist = [func(elt) for elt in somelist]  
  2.  s = "".join(slist) 

2、當對字符串可以使用正則表達式或者內置函數來處理的時候,選擇內置函數。如str.isalpha(),str.isdigit(),str.startswith((‘x’, ‘yz’)),str.endswith((‘x’, ‘yz’))

3、對字符進行格式化比直接串聯讀取要快,因此要使用

  1. out = "%s%s%s%s" % (head, prologue, query, tail) 

而避免

  1. out = "" + head + prologue + query + tail + "" 

使用列表解析(list comprehension)和生成器表達式(generator expression)

列表解析要比在循環中重新構建一個新的list更爲高效,因此我們可以利用這一特性來提高運行的效率。

  1. from time import time  
  2.  t = time()  
  3.  list = ['a','b','is','python','jason','hello','hill','with','phone','test',  
  4.  'dfdf','apple','pddf','ind','basic','none','baecr','var','bana','dd','wrd']  
  5.  total=[]  
  6.  for i in range (1000000):  
  7.  for w in list:  
  8.  total.append(w)  
  9.  print "total run time:"  
  10.  print time()-t 

使用列表解析:

  1. for i in range (1000000):  
  2. a = [w for w in list] 

上述代碼直接運行大概需要17s,而改爲使用列表解析後,運行時間縮短爲9.29s。將近提高了一半。生成器表達式則是在2.4中引入的新內容,語法和列表解析類似,但是在大數據量處理時,生成器表達式的優勢較爲明顯,它並不創建一個列表,只是返回一個生成器,因此效率較高。在上述例子上中代碼a =[w for w in list]修改爲a=(w for w in list),運行時間進一步減少,縮短約爲2.98s。

其他優化技巧

1、如果需要交換兩個變量的值使用a,b=b,a而不是藉助中間變量t=a;a=b;b=t;

  1. >>> from timeit import Timer  
  2. >>> Timer("t=a;a=b;b=t","a=1;b=2").timeit()  
  3. 0.25154118749729365  
  4. >>> Timer("a,bb=b,a","a=1;b=2").timeit()  
  5. 0.17156677734181258  
  6. >> 
  7. > 

2、在循環的時候使用xrange而不是range;使用xrange可以節省大量的系統內存,因爲xrange()在序列中每次調用只產生一個整數元素。而range()將直接返回完整的元素列表,用於循環時會有不必要的開銷。在Python3中xrange不再存在,裏面range提供一個可以遍歷任意長度的範圍的iterator。

3、使用局部變量,避免“global”關鍵字。Python訪問局部變量會比全局變量要快得多,因此可以利用這一特性提升性能。

4、if done is not None比語句if done!=None更快,讀者可以自行驗證;

5、在耗時較多的循環中,可以把函數的調用改爲內聯的方式;

6、使用級聯比較 “x < y < z”而不是“x < y and y < z”;

7、while 1要比while True更快(當然後者的可讀性更好);

8、build in函數通常較快,add(a,b)要優於a+b。

定位程序性能瓶頸

對代碼優化的前提是需要了解性能瓶頸在什麼地方,程序運行的主要時間是消耗在哪裏,對於比較複雜的代碼可以藉助一些工具來定位,Python內置了豐富的性能分析工具,如profile,cProfile與hotshot等。其中Profiler是python自帶的一組程序,能夠描述程序運行時候的性能,並提供各種統計幫助用戶定位程序的性能瓶頸。Python標準模塊提供三種profilers:cProfile,profile以及hotshot。

profile的使用非常簡單,只需要在使用之前進行import即可。具體實例如下:

清單8.使用profile進行性能分析

  1. import profile  
  2. def profileTest():  
  3. Total =1;  
  4. for i in range(10):  
  5. TotalTotal=Total*(i+1)  
  6. print Total  
  7. return Total  
  8. if __name__ == "__main__":  
  9. profile.run("profileTest()") 
 

程序的運行結果如下:

圖 1. 性能分析結果

Python 代碼性能優化技巧

其中輸出每列的具體解釋如下:

  • ncalls:表示函數調用的次數;
  • tottime:表示指定函數的總的運行時間,除掉函數中調用子函數的運行時間;
  • percall:(第一個percall)等於tottime/ncalls;
  • cumtime:表示該函數及其所有子函數的調用運行的時間,即函數開始調用到返回的時間;
  • percall:(第二個percall)即函數運行一次的平均時間,等於cumtime/ncalls;
  • filename:lineno(function):每個函數調用的具體信息;

如果需要將輸出以日誌的形式保存,只需要在調用的時候加入另外一個參數。如profile.run(“profileTest()”,”testprof”)。

對於profile的剖析數據,如果以二進制文件的時候保存結果的時候,可以通過pstats模塊進行文本報表分析,它支持多種形式的報表輸出,是文本界面下一個較爲實用的工具。使用非常簡單:

  1. import pstats  
  2. p = pstats.Stats('testprof')  
  3. p.sort_stats("name").print_stats() 

其中sort_stats()方法能夠對剖分數據進行排序,可以接受多個排序字段,如sort_stats(‘name’, ‘file’)將首先按照函數名稱進行排序,然後再按照文件名進行排序。常見的排序字段有calls(被調用的次數),time(函數內部運行時間),cumulative(運行的總時間)等。此外pstats也提供了命令行交互工具,執行 python–m pstats後可以通過help瞭解更多使用方式。

對於大型應用程序,如果能夠將性能分析的結果以圖形的方式呈現,將會非常實用和直觀,常見的可視化工具有Gprof2Dot,visualpytune,KCacheGrind等,讀者可以自行查閱相關官網,本文不做詳細討論。

Python性能優化工具

Python性能優化除了改進算法,選用合適的數據結構之外,還有幾種關鍵的技術,比如將關鍵Python代碼部分重寫成C擴展模塊,或者選用在性能上更爲優化的解釋器等,這些在本文中統稱爲優化工具。Python有很多自帶的優化工具,如Psyco,Pypy,Cython,Pyrex等,這些優化工具各有千秋,本節選擇幾種進行介紹。

Psyco

Psyco是一個just-in-time的編譯器,它能夠在不改變源代碼的情況下提高一定的性能,Psyco將操作編譯成有點優化的機器碼,其操作分成三個不同的級別,有”運行時”、”編譯時”和”虛擬時”變量。並根據需要提高和降低變量的級別。運行時變量只是常規Python解釋器處理的原始字節碼和對象結構。一旦Psyco將操作編譯成機器碼,那麼編譯時變量就在機器寄存器和可直接訪問的內存位置中表示。同時Python能高速緩存已編譯的機器碼以備今後重用,這樣能節省一點時間。但Psyco也有其缺點,其本身運行所佔內存較大。目前Psyco已經不在Python2.7中支持,而且不再提供維護和更新了,對其感興趣的可以參考ttp://psyco.sourceforge.net/

Pypy

Pypy表示“用Python實現的Python”,但實際上它是使用一個稱爲RPython的Python子集實現的,能夠將Python代碼轉成C,.NET,Java等語言和平臺的代碼。PyPy 集成了一種即時 (JIT)編譯器。和許多編譯器,解釋器不同,它不關心Python代碼的詞法分析和語法樹。因爲它是用Python語言寫的,所以它直接利用Python語言的Code Object。Code Object是Python字節碼的表示,也就是說,PyPy直接分析Python代碼所對應的字節碼,這些字節碼即不是以字符形式也不是以某種二進制格式保存在文件中,而在Python運行環境中。目前版本是1.8.支持不同的平臺安裝,Windows上安裝Pypy需要先下載,然後解壓到相關的目錄,並將解壓後的路徑添加到環境變量path中即可。在命令行運行Pypy,如果出現如下錯誤:”沒有找到MSVCR100.dll, 因此這個應用程序未能啓動,重新安裝應用程序可能會修復此問題”,則還需要在微軟的官網上下載VS 2010 runtime libraries解決該問題。

安裝成功後在命令行裏運行Pypy,輸出結果如下:

  1. C:\Documents and Settings\Administrator>pypy  
  2.  
  3. Python 2.7.2 (0e28b379d8b3, Feb 09 2012, 18:31:47)  
  4.  
  5. [PyPy 1.8.0 with MSC v.1500 32 bit] on win32  
  6.  
  7. Type "help", "copyright", "credits" or "license" for more information.  
  8.  
  9. And now for something completely different: ``PyPy is vast, and contains  
  10.  
  11. multitudes''  
  12.  
  13. >>>> 

以清單5的循環爲例子,使用Python和Pypy分別運行,得到的運行結果分別如下:

  1. C:\Documents and Settings\Administrator\ 桌面 \doc\python>pypy loop.py  
  2.  
  3. total run time:  
  4.  
  5. 8.42199993134  
  6.  
  7. C:\Documents and Settings\Administrator\ 桌面 \doc\python>python loop.py  
  8.  
  9. total run time:  
  10.  
  11. 106.391000032 

可見使用Pypy來編譯和運行程序,其效率大大的提高。

Cython

Cython是用Python實現的一種語言,可以用來寫Python擴展,用它寫出來的庫都可以通過import來載入,性能上比Python的快。Cython裏可以載入Python擴展(比如 import math),也可以載入C的庫的頭文件(比如:cdef extern from “math.h”),另外也可以用它來寫Python代碼。將關鍵部分重寫成C擴展模塊

Linux Cpython的安裝:

第一步:下載

  1. [root@v5254085f259 cpython]# wget -N http://cython.org/release/Cython-0.15.1.zip  
  2.  
  3. --2012-04-16 22:08:35-- http://cython.org/release/Cython-0.15.1.zip  
  4.  
  5. Resolving cython.org... 128.208.160.197  
  6.  
  7. Connecting to cython.org|128.208.160.197|:80... connected.  
  8.  
  9. HTTP request sent, awaiting response... 200 OK  
  10.  
  11. Length: 2200299 (2.1M) [application/zip]  
  12.  
  13. Saving to: `Cython-0.15.1.zip'  
  14.  
  15. 100%[======================================>] 2,200,299 1.96M/s in 1.1s  
  16.  
  17. 2012-04-16 22:08:37 (1.96 MB/s) - `Cython-0.15.1.zip' saved [2200299/2200299] 

第二步:解壓

  1. [root@v5254085f259 cpython]# unzip -o Cython-0.15.1.zip 

第三步:安裝

  1. python setup.py install 

安裝完成後直接輸入Cython,如果出現如下內容則表明安裝成功。

  1. [root@v5254085f259 Cython-0.15.1]# cython  
  2.  
  3. Cython (http://cython.org) is a compiler for code written in the  
  4.  
  5. Cython language. Cython is based on Pyrex by Greg Ewing.  
  6.  
  7. Usage: cython [options] sourcefile.{pyx,py} ...  
  8.  
  9. Options:  
  10.  
  11. -V, --version Display version number of cython compiler  
  12.  
  13. -l, --create-listing Write error messages to a listing file  
  14.  
  15. -I, --include-dir <directory> Search for include files in named directory  
  16.  
  17. (multiple include directories are allowed).  
  18.  
  19. -o, --output-file <filename> Specify name of generated C file  
  20.  
  21. -t, --timestamps Only compile newer source files  
  22.  
  23. -f, --force Compile all source files (overrides implied -t)  
  24.  
  25. -q, --quiet Don't print module names in recursive mode  
  26.  
  27. -v, --verbose Be verbose, print file names on multiple compil ation  
  28.  
  29. -p, --embed-positions If specified, the positions in Cython files of each  
  30.  
  31. function definition is embedded in its docstring.  
  32.  
  33. --cleanup <level> 
  34.  
  35. Release interned objects on python exit, for memory debugging.  
  36.  
  37. Level indicates aggressiveness, default 0 releases nothing.  
  38.  
  39. -w, --working <directory> 
  40.  
  41. Sets the working directory for Cython (the directory modules are searched from)  
  42.  
  43. --gdb Output debug information for cygdb  
  44.  
  45. -D, --no-docstrings  
  46.  
  47. Strip docstrings from the compiled module.  
  48.  
  49. -a, --annotate  
  50.  
  51. Produce a colorized HTML version of the source.  
  52.  
  53. --line-directives  
  54.  
  55. Produce #line directives pointing to the .pyx source  
  56.  
  57. --cplus  
  58.  
  59. Output a C++ rather than C file.  
  60.  
  61. --embed[=<method_name>]  
  62.  
  63. Generate a main() function that embeds the Python interpreter.  
  64.  
  65. -2 Compile based on Python-2 syntax and code seman tics.  
  66.  
  67. -3 Compile based on Python-3 syntax and code seman tics.  
  68.  
  69. --fast-fail Abort the compilation on the first error  
  70.  
  71. --warning-error, -Werror Make all warnings into errors  
  72.  
  73. --warning-extra, -Wextra Enable extra warnings  
  74.  
  75. -X, --directive <name>=<value> 
  76.  
  77. [,<namename=value,...] Overrides a compiler directive 

其他平臺上的安裝可以參考文檔:http://docs.cython.org/src/quickstart/install.html

Cython代碼與Python不同,必須先編譯,編譯一般需要經過兩個階段,將pyx文件編譯爲.c 文件,再將.c 文件編譯爲.so 文件。編譯有多種方法:

  • 通過命令行編譯:

假設有如下測試代碼,使用命令行編譯爲.c文件。

  1. [root@v5254085f259 test]# gcc -shared -pthread -fPIC -fwrapv -O2  
  2.  
  3. -Wall -fno-strict-aliasing -I/usr/include/python2.4 -o sum.so sum.c  
  4.  
  5. [root@v5254085f259 test]# ls  
  6.  
  7. total 96  
  8.  
  9. 4 drwxr-xr-x 2 root root 4096 Apr 17 02:47 .  
  10.  
  11. 4 drwxr-xr-x 4 root root 4096 Apr 16 22:20 ..  
  12.  
  13. 4 -rw-r--r-- 1 root root 35 Apr 17 02:45 1  
  14.  
  15. 60 -rw-r--r-- 1 root root 55169 Apr 17 02:45 sum.c  
  16.  
  17. 4 -rw-r--r-- 1 root root 35 Apr 17 02:45 sum.pyx  
  18.  
  19. 20 -rwxr-xr-x 1 root root 20307 Apr 17 02:47 sum.so 
  • 使用distutils編譯

建立一個setup.py的腳本:

  1. from distutils.core import setup  
  2.  
  3. from distutils.extension import Extension  
  4.  
  5. from Cython.Distutils import build_ext  
  6.  
  7. ext_modules = [Extension("sum", ["sum.pyx"])]  
  8.  
  9. setup(  
  10.  
  11. name = 'sum app',  
  12.  
  13. cmdclass = {'build_ext': build_ext},  
  14.  
  15. ext_modulesext_modules = ext_modules  
  16.  
  17. )  
  18.  
  19. [root@v5254085f259 test]# python setup.py build_ext --inplace  
  20.  
  21. running build_ext  
  22.  
  23. cythoning sum.pyx to sum.c  
  24.  
  25. building 'sum' extension  
  26.  
  27. gcc -pthread -fno-strict-aliasing -fPIC -g -O2 -DNDEBUG -g -fwrapv -O3  
  28.  
  29. -Wall -Wstrict-prototypes -fPIC -I/opt/ActivePython-2.7/include/python2.7  
  30.  
  31. -c sum.c -o build/temp.linux-x86_64-2.7/sum.o  
  32.  
  33. gcc -pthread -shared build/temp.linux-x86_64-2.7/sum.o  
  34.  
  35. -o /root/cpython/test/sum.so 

編譯完成之後可以導入到Python中使用:

  1. [root@v5254085f259 test]# python  
  2.  
  3. ActivePython 2.7.2.5 (ActiveState Software Inc.) based on  
  4.  
  5. Python 2.7.2 (default, Jun 24 2011, 11:24:26)  
  6.  
  7. [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2  
  8.  
  9. Type "help", "copyright", "credits" or "license" for more information.  
  10.  
  11. >>> import pyximport; pyximport.install()  
  12.  
  13. >>> import sum  
  14.  
  15. >>> sum.sum(1,3) 

下面來進行一個簡單的性能比較:

清單9.Cython測試代碼

  1. from time import time  
  2.  
  3. def test(int n):  
  4.  
  5. cdef int a =0 
  6.  
  7. cdef int i  
  8.  
  9. for i in xrange(n):  
  10.  
  11. a+= i  
  12.  
  13. return a  
  14.  
  15. t = time()  
  16.  
  17. test(10000000)  
  18.  
  19. print "total run time:"  
  20.  
  21. print time()-t 

測試結果:

  1. [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2  
  2.  
  3. Type "help", "copyright", "credits" or "license" for more information.  
  4.  
  5. >>> import pyximport; pyximport.install()  
  6.  
  7. >>> import ctest  
  8.  
  9. total run time:  
  10.  
  11. 0.00714015960693 

清單10.Python測試代碼

  1. from time import time  
  2.  
  3. def test(n):  
  4.  
  5. a =0;  
  6.  
  7. for i in xrange(n):  
  8.  
  9. a+= i  
  10.  
  11. return a  
  12.  
  13. t = time()  
  14.  
  15. test(10000000)  
  16.  
  17. print "total run time:"  
  18.  
  19. print time()-t  
  20.  
  21. [root@v5254085f259 test]# python test.py  
  22.  
  23. total run time:  
  24.  
  25. 0.971596002579 

從上述對比可以看到使用Cython的速度提高了將近100多倍。

總結

本文初步探討了Python常見的性能優化技巧以及如何藉助工具來定位和分析程序的性能。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章