Python写法纠正和优化:
bad | good |
if x == None: ... | if x is None: ... |
mapping = {5 : "5", 6 : "6"} | # Use iter* methods when possible |
if x < 10 and x > 2: ... | if 2 < x < 10: ... |
al = [1, 2, 3] | al = [1, 2, 3] |
if x == 1: y = fun1(x) | if x == 1: y = fun1(x) |
from operator import add | sl = ["ab", "cd", "ef"] |
a = "this isn't a word, right?" | # .replace can be fine. This is faster: |
class Foo(object): | # Generally getters and setters are not used. |
a = "this isn't a word, right?" | # .replace can be fine. This is faster: |
def mul(x, y): return x*y | def mul(x, y): |
l = [0] * 4 | # One correct way to create a matrix: |
# sorting on the second item of the tuple | from operator import itemgetter 根据元组第二项排序 |
vals = [5, 7 ,8] | vals = [5, 7 ,8] |
ll = [[1, 2, 3], [4], [5, 6]] | data = [[1, 2, 3], [4], [5, 6]] |
# To negate (inplace) each second | from operator import neg 偶数项变负数 |
freqs = {} | # Short way: |
someitems = set([1, 2, 3]) | someitems = set([1, 2, 3]) |
from time import clock | # This works well on Windows and Linux: |
参照:
Python best practices:
http://www.fantascienza.net/leonardo/ar/python_best_practices.html
python性能提升:
1. python快速的内建函数
input, int, isinstance, issubclass, iter, open, ord, pow, print, property
2. jion连接字符串更快,因为+会创建一个新的字符串并复制旧的内容
同理,list用extend更快
3. 快速交换变量,不用temp
x, y = y, x
4. 尽量使用局部变量
5. 尽量使用in
6. 使用延迟加载加速:将import移入函数中,需要时再导入,可以加速软件启动
可以多用from……import……
7. while 1:比while True:高效
8. list comprehension(列表解析)比for,while快
eg:evens = [i for i in range(10) if i % 2 == 0]
9. xrange是range的兄弟,用于需要节省内存和超大数据集合
xrange不生成整个列表
10. itertools模块,迭代组合
11. python中列表是数组,append是尾部添加,比insert首部添加要高效
deque是双链表
dict,set是哈希表
12. Schwartzian Transform准则
装饰——排序——去装饰
例如:使用list.sort比list.sort(cmp)高效(cmp是自己编写的函数),因此对其他结构排序,可以将其他结构装换为list
13. GIL全局解释器锁会序列化线程,可以考虑用multiprocessing
参照:
《python性能鸡汤》:
中文翻译:http://blog.renren.com/share/101978396/12376358005
英文原文:http://blog.monitis.com/index.php/2012/02/13/python-performance-tips-part-1/
英文原文:http://blog.monitis.com/index.php/2012/03/21/python-performance-tips-part-2/
实用工具:
1. python -m profile 程序
性能监控
eg:
python –m profile –o stats x.py
>>> import stats
>>> p = pstats.Stats(‘stats’) # stats为记录文件
>>> p.sort_stats(‘time’).print_stats(15)
详情参照:
python用profile:
http://blog.youkuaiyun.com/lanphaday/article/details/1483728
2. 一些有用的第三方库和工具:
NumPy:和Matlab差不多
Scipy:数值处理
GPULib
PyPy:JIT编译器,优化python代码
CPython,Boost等:python -> C
ShedSkin: python -> C++