您的位置:首页 > 编程语言 > Python开发

第四部分:python性能技巧

2016-03-16 20:49 309 查看
4.1 查询操作为主时,选择字典结构比list结构效率更高

4.2 取list的交集、并集、差集时,可借助set数据结构
如listintersection = list(set(lista)&set(listb))
4.3 原则是尽量减少循环过程中的计算量,有多重循环的尽量将内层的计算提到上一层.所以可以在外层实现的内层计算要在外层完成,然后传值进去。
4.4 python 中的字符串对象是不可改变的,因此对任何字符串的操作如拼接,修改等都将产生一个新的字符串对象,而不是基于原字符串.
对于字符串的操作,尽量使用下列方法
(1)在字符串连接的使用尽量使用 join() 而不是 + 号。
(2)当对字符串可以使用正则表达式或者内置函数来处理的时候,选择内置函数。
如 str.isalpha(),str.isdigit(),str.startswith(('x', 'yz')),str.endswith(('x', 'yz'))
(3)对字符进行格式化比直接串联读取要快,因此要使用out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
4.5 尽量使用局部变量,避免全局变量,python访问局部变量的速度比访问全局变量的速度更快
4.6 if done is not None 比语句 if done != None 更快
4.7 使用级联比较 "x < y < z" 而不是 "x < y and y < z"
4.8 build in 函数通常较快,add(a,b) 要优于 a+
4.9 python内置了性能分析工具,如profile,hotshot,与cProfile.
示例1, 以profile为例:
import profile
def profileTest():
Total =1;
for i in range(10):
Total=Total*(i+1)
print Total
return Total
if __name__ == "__main__":
profile.run("profileTest()")
运行结果:
1
2
6
24
120
720
5040
40320
362880
3628800
5 function calls in 0.083 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(range)
1 0.082 0.082 0.082 0.082 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.083 0.083 profile:0(profileTest())
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 0.000 0.000 python.py:2(profileTest)
4.10 常用的python 自带的优化工具,如 Psyco,Pypy,Cython,Pyrex
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: