天天看點

【原創】Python 之快速性能優化(第二部分)

this is the part ii of quick python performance optimizations. 

本文是 python 性能優化二兩發的第二部分。 

11. use map, reduce and filter instead of for loop where ever possible. 

11. 盡可能使用 map,reduce 和 filter 替代 for 循環。 

12. for checking 'a in b', dict or set is better than list/tuple. 

12. 針對 'a in b' 的測試,b 是字典或者集合要好于是清單/元組的情況。 

13. while working with big amount of data, if possible use immutable datatypes, they are faster - tuples > list 

13. 當針對大塊資料進行操作時,在可能的情況下,使用不可變資料類型更好,因為它們會更快相應操作 - 元組 > 清單。 

14. insertion into a list in o(n) complexity. 

14. 向清單插入資料是 o(n) 複雜度的操作。 

15. if you need manipulations on both ends of a list, use deque. 

15. 如果你需要對清單的頭和尾都進行操作,請使用 deque 。 

16. del - delete the objects after use - 

python does it by itself. but make sure of that with the gc module or 

by writing an __del__ magic function or 

the simplest way, del after use.

16. del - 在對象使用結束後進行删除 -  

python 自己會進行該操作。但是請确認 gc 子產品處于正常工作狀态,或

自己寫一個 __del__ magic 函數,或

最簡單的方式,自己在用後自己删除。

17. time.clock() 

17. 使用 time.clock() 。 

18. gil(http://wiki.python.org/moin/globalinterpreterlock) - gil is a demon.  

gil allows only one python native thread to be run per process, preventing cpu level parallelism. try using ctypes and native c libararies to overcome this. when even you reach the end of optimizing with python, always there exist an option of rewriting terribly slow functions in native c, and using it through python c bindings. other libraries like gevent is also attacking the problem, and is successful to some extend.  

gil 隻允許在每個程序裡運作一個 python 本地線程,阻止了 cpu 級别的并發。可以使用 ctypes 和純 c 庫來解決這個問題。就算到了優化 python 代碼的最後階段,仍舊可以通過使用純 c 重寫慢速 python 函數來進行優化。或者幹脆直接使用 python 的 c 綁定。其他的庫,如 gevent,同樣也針對此問題進行了優化,從某種角度上來說還是不錯的。 

tl,dr: while you write code, just give one round of thought on the data structures, the iteration constructs, builtins and create c extensions for tricking the gil if need. 

tl,dr: 當你寫代碼的時候,可以在資料結構、疊代的建構、内置函數上多進行一些考量 ,并在必要時,建立一些 c 擴充來克服 gil 帶來的問題。