自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python代碼性能優(yōu)化技巧

開(kāi)發(fā) 后端
代碼優(yōu)化能夠讓程序運(yùn)行更快,它是在不改變程序運(yùn)行結(jié)果的情況下使得程序的運(yùn)行效率更高,根據(jù) 80/20 原則,實(shí)現(xiàn)程序的重構(gòu)、優(yōu)化、擴(kuò)展以及文檔相關(guān)的事情通常需要消耗 80% 的工作量。優(yōu)化通常包含兩方面的內(nèi)容:減小代碼的體積,提高代碼的運(yùn)行效率。

代碼優(yōu)化能夠讓程序運(yùn)行更快,它是在不改變程序運(yùn)行結(jié)果的情況下使得程序的運(yùn)行效率更高,根據(jù) 80/20 原則,實(shí)現(xiàn)程序的重構(gòu)、優(yōu)化、擴(kuò)展以及文檔相關(guān)的事情通常需要消耗 80% 的工作量。優(yōu)化通常包含兩方面的內(nèi)容:減小代碼的體積,提高代碼的運(yùn)行效率。

改進(jìn)算法,選擇合適的數(shù)據(jù)結(jié)構(gòu)

一個(gè)良好的算法能夠?qū)π阅芷鸬疥P(guān)鍵作用,因此性能改進(jìn)的首要點(diǎn)是對(duì)算法的改進(jìn)。在算法的時(shí)間復(fù)雜度排序上依次是:

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

因此如果能夠在時(shí)間復(fù)雜度上對(duì)算法進(jìn)行一定的改進(jìn),對(duì)性能的提高不言而喻。但對(duì)具體算法的改進(jìn)不屬于本文討論的范圍,讀者可以自行參考這方面資料。下面的內(nèi)容將集中討論數(shù)據(jù)結(jié)構(gòu)的選擇。

字典 (dictionary) 與列表 (list)

Python 字典中使用了 hash table,因此查找操作的復(fù)雜度為 O(1),而 list 實(shí)際是個(gè)數(shù)組,在 list 中,查找需要遍歷整個(gè) list,其復(fù)雜度為 O(n),因此對(duì)成員的查找訪問(wè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 

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

集合 (set) 與列表 (list)

set 的 union, intersection,difference 操作要比 list 的迭代要快。因此如果涉及到求 list 交集,并集或者差的問(wèn)題可以轉(zhuǎn)換為 set 來(lái)操作。

清單 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 

上述程序的運(yùn)行時(shí)間大概為:

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 后程序的運(yùn)行時(shí)間縮減為 8.75,提高了 4 倍多,運(yùn)行時(shí)間大大縮短。讀者可以自行使用表 1 其他的操作進(jìn)行測(cè)試。

表 1. set 常見(jiàn)用法

語(yǔ)法                                   操作                       說(shuō)明

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

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

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

對(duì)循環(huán)的優(yōu)化

對(duì)循環(huán)的優(yōu)化所遵循的原則是盡量減少循環(huán)過(guò)程中的計(jì)算量,有多重循環(huán)的盡量將內(nèi)層的計(jì)算提到上一層。 下面通過(guò)實(shí)例來(lái)對(duì)比循環(huán)優(yōu)化后所帶來(lái)的性能的提高。程序清單 4 中,如果不進(jìn)行循環(huán)優(yōu)化,其大概的運(yùn)行時(shí)間約為 132.375。

清單 4. 為進(jìn)行循環(huán)優(yōu)化前

  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 

現(xiàn)在進(jìn)行如下優(yōu)化,將長(zhǎng)度計(jì)算提到循環(huán)外,range 用 xrange 代替,同時(shí)將第三層的計(jì)算 lista[a] 提到循環(huán)的第二層。

清單 5. 循環(huán)優(yōu)化后

  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.  len1=len(lista)  
  6.  len2=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 

上述優(yōu)化后的程序其運(yùn)行時(shí)間縮短為 102.171999931。在清單 4 中 lista[a] 被計(jì)算的次數(shù)為 1000000*10*10,而在優(yōu)化后的代碼中被計(jì)算的次數(shù)為 1000000*10,計(jì)算次數(shù)大幅度縮短,因此性能有所提升。

充分利用 Lazy if-evaluation 的特性

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

清單 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 

在未進(jìn)行優(yōu)化之前程序的運(yùn)行時(shí)間大概為 8.84,如果使用注釋行代替第一個(gè) if,運(yùn)行的時(shí)間大概為 6.17。

字符串的優(yōu)化

python 中的字符串對(duì)象是不可改變的,因此對(duì)任何字符串的操作如拼接,修改等都將產(chǎn)生一個(gè)新的字符串對(duì)象,而不是基于原字符串,因此這種持續(xù)的 copy 會(huì)在一定程度上影響 python 的性能。對(duì)字符串的優(yōu)化也是改善性能的一個(gè)重要的方面,特別是在處理文本較多的情況下。字符串的優(yōu)化主要集中在以下幾個(gè)方面:

1、在字符串連接的使用盡量使用 join() 而不是 +:在代碼清單 7 中使用 + 進(jìn)行字符串連接大概需要 0.125 s,而使用 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 

同時(shí)要避免:

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

而是要使用:

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

2、當(dāng)對(duì)字符串可以使用正則表達(dá)式或者內(nèi)置函數(shù)來(lái)處理的時(shí)候,選擇內(nèi)置函數(shù)。如 str.isalpha(),str.isdigit(),str.startswith((‘x’, ‘yz’)),str.endswith((‘x’, ‘yz’))

3、對(duì)字符進(jìn)行格式化比直接串聯(lián)讀取要快,因此要使用

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

而避免

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

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

列表解析要比在循環(huán)中重新構(gòu)建一個(gè)新的 list 更為高效,因此我們可以利用這一特性來(lái)提高運(yùn)行的效率。

  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] 

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

#p#

其他優(yōu)化技巧

1、如果需要交換兩個(gè)變量的值使用 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,b=b,a","a=1;b=2").timeit()  
  5.  0.17156677734181258 
  6.  >>  

2、在循環(huán)的時(shí)候使用 xrange 而不是 range;使用 xrange 可以節(jié)省大量的系統(tǒng)內(nèi)存,因?yàn)?xrange() 在序列中每次調(diào)用只產(chǎn)生一個(gè)整數(shù)元素。而 range() 將直接返回完整的元素列表,用于循環(huán)時(shí)會(huì)有不必要的開(kāi)銷。在 python3 中 xrange 不再存在,里面 range 提供一個(gè)可以遍歷任意長(zhǎng)度的范圍的 iterator。

3、使用局部變量,避免”global” 關(guān)鍵字。python 訪問(wèn)局部變量會(huì)比全局變量要快得多,因 此可以利用這一特性提升性能。

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

5、在耗時(shí)較多的循環(huán)中,可以把函數(shù)的調(diào)用改為內(nèi)聯(lián)的方式;

6、使用級(jí)聯(lián)比較 “x < y < z” 而不是 “x < y and y < z”;

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

8、build in 函數(shù)通常較快,add(a,b) 要優(yōu)于 a+b。

定位程序性能瓶頸

對(duì)代碼優(yōu)化的前提是需要了解性能瓶頸在什么地方,程序運(yùn)行的主要時(shí)間是消耗在哪里,對(duì)于比較復(fù)雜的代碼可以借助一些工具來(lái)定位,python 內(nèi)置了豐富的性能分析工具,如 profile,cProfile 與 hotshot 等。其中 Profiler 是 python 自帶的一組程序,能夠描述程序運(yùn)行時(shí)候的性能,并提供各種統(tǒng)計(jì)幫助用戶定位程序的性能瓶頸。Python 標(biāo)準(zhǔn)模塊提供三種 profilers:cProfile,profile 以及 hotshot。

profile 的使用非常簡(jiǎn)單,只需要在使用之前進(jìn)行 import 即可。具體實(shí)例如下:

清單 8. 使用 profile 進(jìn)行性能分析

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

程序的運(yùn)行結(jié)果如下:

圖 1. 性能分析結(jié)果

Python 代碼性能優(yōu)化技巧

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

●ncalls:表示函數(shù)調(diào)用的次數(shù);

●tottime:表示指定函數(shù)的總的運(yùn)行時(shí)間,除掉函數(shù)中調(diào)用子函數(shù)的運(yùn)行時(shí)間;

●percall:(第一個(gè) percall)等于 tottime/ncalls;

●cumtime:表示該函數(shù)及其所有子函數(shù)的調(diào)用運(yùn)行的時(shí)間,即函數(shù)開(kāi)始調(diào)用到返回的時(shí)間;

●percall:(第二個(gè) percall)即函數(shù)運(yùn)行一次的平均時(shí)間,等于 cumtime/ncalls;

●filename:lineno(function):每個(gè)函數(shù)調(diào)用的具體信息;

如果需要將輸出以日志的形式保存,只需要在調(diào)用的時(shí)候加入另外一個(gè)參數(shù)。如 profile.run(“profileTest()”,”testprof”)。

對(duì)于 profile 的剖析數(shù)據(jù),如果以二進(jìn)制文件的時(shí)候保存結(jié)果的時(shí)候,可以通過(guò) pstats 模塊進(jìn)行文本報(bào)表分析,它支持多種形式的報(bào)表輸出,是文本界面下一個(gè)較為實(shí)用的工具。使用非常簡(jiǎn)單:

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

其中 sort_stats() 方法能夠?qū)ζ史謹(jǐn)?shù)據(jù)進(jìn)行排序, 可以接受多個(gè)排序字段,如 sort_stats(‘name’, ‘file’) 將首先按照函數(shù)名稱進(jìn)行排序,然后再按照文件名進(jìn)行排序。常見(jiàn)的排序字段有 calls( 被調(diào)用的次數(shù) ),time(函數(shù)內(nèi)部運(yùn)行時(shí)間),cumulative(運(yùn)行的總時(shí)間)等。此外 pstats 也提供了命令行交互工具,執(zhí)行 python – m pstats 后可以通過(guò) help 了解更多使用方式。

對(duì)于大型應(yīng)用程序,如果能夠?qū)⑿阅芊治龅慕Y(jié)果以圖形的方式呈現(xiàn),將會(huì)非常實(shí)用和直觀,常見(jiàn)的可視化工具有 Gprof2Dot,visualpytune,KCacheGrind 等,讀者可以自行查閱相關(guān)官網(wǎng),本文不做詳細(xì)討論。

#p#

Python 性能優(yōu)化工具

Python 性能優(yōu)化除了改進(jìn)算法,選用合適的數(shù)據(jù)結(jié)構(gòu)之外,還有幾種關(guān)鍵的技術(shù),比如將關(guān)鍵 python 代碼部分重寫(xiě)成 C 擴(kuò)展模塊,或者選用在性能上更為優(yōu)化的解釋器等,這些在本文中統(tǒng)稱為優(yōu)化工具。python 有很多自帶的優(yōu)化工具,如 Psyco,Pypy,Cython,Pyrex 等,這些優(yōu)化工具各有千秋,本節(jié)選擇幾種進(jìn)行介紹。

Psyco

psyco 是一個(gè) just-in-time 的編譯器,它能夠在不改變?cè)创a的情況下提高一定的性能,Psyco 將操作編譯成有點(diǎn)優(yōu)化的機(jī)器碼,其操作分成三個(gè)不同的級(jí)別,有”運(yùn)行時(shí)”、”編譯時(shí)”和”虛擬時(shí)”變量。并根據(jù)需要提高和降低變量的級(jí)別。運(yùn)行時(shí)變量只是常規(guī) Python 解釋器處理的原始字節(jié)碼和對(duì)象結(jié)構(gòu)。一旦 Psyco 將操作編譯成機(jī)器碼,那么編譯時(shí)變量就會(huì)在機(jī)器寄存器和可直接訪問(wèn)的內(nèi)存位置中表示。同時(shí) python 能高速緩存已編譯的機(jī)器碼以備今后重用,這樣能節(jié)省一點(diǎn)時(shí)間。但 Psyco 也有其缺點(diǎn),其本身運(yùn)行所占內(nèi)存較大。目前 psyco 已經(jīng)不在 python2.7 中支持,而且不再提供維護(hù)和更新了,對(duì)其感興趣的可以參考 http://psyco.sourceforge.net/

Pypy

PyPy 表示 “用 Python 實(shí)現(xiàn)的 Python”,但實(shí)際上它是使用一個(gè)稱為 RPython 的 Python 子集實(shí)現(xiàn)的,能夠?qū)?Python 代碼轉(zhuǎn)成 C, .NET, Java 等語(yǔ)言和平臺(tái)的代碼。PyPy 集成了一種即時(shí) (JIT) 編譯器。和許多編譯器,解釋器不同,它不關(guān)心 Python 代碼的詞法分析和語(yǔ)法樹(shù)。 因?yàn)樗怯?Python 語(yǔ)言寫(xiě)的,所以它直接利用 Python 語(yǔ)言的 Code Object.。 Code Object 是 Python 字節(jié)碼的表示,也就是說(shuō), PyPy 直接分析 Python 代碼所對(duì)應(yīng)的字節(jié)碼 ,,這些字節(jié)碼即不是以字符形式也不是以某種二進(jìn)制格式保存在文件中, 而在 Python 運(yùn)行環(huán)境中。目前版本是 1.8. 支持不同的平臺(tái)安裝,windows 上安裝 Pypy 需要先下載https://bitbucket.org/pypy/pypy/downloads/pypy-1.8-win32.zip,然后解壓到相關(guān)的目錄,并將解壓后的路徑添加到環(huán)境變量 path 中即可。在命令行運(yùn)行 pypy,如果出現(xiàn)如下錯(cuò)誤:”沒(méi)有找到 MSVCR100.dll, 因此這個(gè)應(yīng)用程序未能啟動(dòng),重新安裝應(yīng)用程序可能會(huì)修復(fù)此問(wèn)題”,則還需要在微軟的官網(wǎng)上下載 VS 2010 runtime libraries 解決該問(wèn)題。具體地址為http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=5555

安裝成功后在命令行里運(yùn)行 pypy,輸出結(jié)果如下:

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

以清單5 的循環(huán)為例子,使用 python 和 pypy 分別運(yùn)行,得到的運(yùn)行結(jié)果分別如下:

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

可見(jiàn)使用 pypy 來(lái)編譯和運(yùn)行程序,其效率大大的提高。

Cython

Cython 是用 python 實(shí)現(xiàn)的一種語(yǔ)言,可以用來(lái)寫(xiě) python 擴(kuò)展,用它寫(xiě)出來(lái)的庫(kù)都可以通過(guò) import 來(lái)載入,性能上比 python 的快。cython 里可以載入 python 擴(kuò)展 ( 比如 import math),也可以載入 c 的庫(kù)的頭文件 ( 比如 :cdef extern from “math.h”),另外也可以用它來(lái)寫(xiě) python 代碼。將關(guān)鍵部分重寫(xiě)成 C 擴(kuò)展模塊

Linux Cpython 的安裝:

第一步:下載

  1. [root@v5254085f259 cpython]# wget -N http://cython.org/release/Cython-0.15.1.zip  
  2.  --2012-04-16 22:08:35-- http://cython.org/release/Cython-0.15.1.zip 
  3.  Resolving cython.org... 128.208.160.197 
  4.  Connecting to cython.org|128.208.160.197|:80... connected.  
  5.  HTTP request sent, awaiting response... 200 OK  
  6.  Length: 2200299 (2.1M) [application/zip]  
  7.  Saving to: `Cython-0.15.1.zip'  
  8. 100%[======================================>] 2,200,299 1.96M/s in 1.1s 
  9. 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,如果出現(xiàn)如下內(nèi)容則表明安裝成功。

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

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

Cython 代碼與 python 不同,必須先編譯,編譯一般需要經(jīng)過(guò)兩個(gè)階段,將 pyx 文件編譯為 .c 文件,再將 .c 文件編譯為 .so 文件。編譯有多種方法:

通過(guò)命令行編譯:

假設(shè)有如下測(cè)試代碼,使用命令行編譯為 .c 文件。

  1. def sum(int a,int b):  
  2.         print a+b  
  3.    
  4.  [root@v5254085f259 test]# cython sum.pyx  
  5.  [root@v5254085f259 test]# ls  
  6.  total 76 
  7.  4 drwxr-xr-x 2 root root  4096 Apr 17 02:45 .  
  8.  4 drwxr-xr-x 4 root root  4096 Apr 16 22:20 ..  
  9.  4 -rw-r--r-- 1 root root    35 Apr 17 02:45 1 
  10.  60 -rw-r--r-- 1 root root 55169 Apr 17 02:45 sum.c  
  11.  4 -rw-r--r-- 1 root root    35 Apr 17 02:45 sum.pyx 

在 linux 上利用 gcc 編譯為 .so 文件:

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

 

使用 distutils 編譯

建立一個(gè) setup.py 的腳本:

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

編譯完成之后可以導(dǎo)入到 python 中使用:

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

下面來(lái)進(jìn)行一個(gè)簡(jiǎn)單的性能比較:

清單 9. Cython 測(cè)試代碼

  1. from time import time  
  2.  def test(int n):  
  3.  cdef int a =0 
  4.  cdef int i  
  5.  for i in xrange(n):  
  6.  a+= i  
  7.  return a  
  8. t = time()  
  9.  test(10000000)  
  10.  print "total run time:" 
  11.  print time()-t 

測(cè)試結(jié)果:

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

清單 10. Python 測(cè)試代碼

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

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

總結(jié)

本文初步探討了 python 常見(jiàn)的性能優(yōu)化技巧以及如何借助工具來(lái)定位和分析程序的性能瓶頸,并提供了相關(guān)可以進(jìn)行性能優(yōu)化的工具或語(yǔ)言,希望能夠更相關(guān)人員一些參考。

責(zé)任編輯:林師授 來(lái)源: developerWorks
相關(guān)推薦

2011-06-14 11:14:10

性能優(yōu)化代碼

2009-11-27 13:24:20

PHP代碼性能優(yōu)化

2015-09-16 14:47:14

Android性能優(yōu)化代碼

2009-06-16 16:39:49

Hibernate性能

2024-08-06 16:31:32

2019-08-21 10:53:29

.NET性能優(yōu)化

2013-06-08 14:19:05

性能優(yōu)化KVM

2011-07-11 15:26:49

性能優(yōu)化算法

2009-12-09 17:33:22

PHP性能優(yōu)化

2019-02-25 07:07:38

技巧React 優(yōu)化

2024-09-14 11:23:19

2022-04-01 15:17:05

Java開(kāi)發(fā)技巧

2024-12-05 09:02:00

Pythonif?

2011-06-14 14:17:23

性能優(yōu)化系統(tǒng)層次

2024-10-09 23:32:50

2011-06-14 14:32:46

性能優(yōu)化

2011-06-14 13:48:07

性能優(yōu)化工具

2024-08-26 11:50:08

2024-06-04 07:46:05

2017-08-08 09:45:43

Python性能優(yōu)化
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)