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. 18. GIL - GIL 是一个恶魔 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 带来的问题。