python性能优化
来源:互联网 发布:店宝宝软件怎么样 编辑:程序博客网 时间:2024/05/20 15:40
性能的优化,无非是从两个方面做。一方面是架构上的优化,使用更高性能的架构;另一方面就是从代码层面,更改代码的写法、算法,从而进行优化。
在我看来,不同的程序员,由于思想的不同、性格的不同,写出来的程序,也一定不同。好的代码,应该是一件艺术品,应该是精雕细琢、巧夺天工的。这样才会有最优雅的外观,最强大的性能。下面就一点点说明,如何将python的性能,从代码层面,提高一倍、十倍、甚至百倍。
慎用python内置函数
python内置函数,只是为了应对通用情况。在很多情况下,内置函数的性能,远远不如自己写的,有针对性的函数。动动手,换个算法,就能把性能提高一倍以上。
1,例子:把字符串 '01_HX' 分别提取出'_'前面和'_'后面的字符串。
你会怎么做?用split('_'),还是切片?我想,很多朋友肯定都会用split('_')。
我们来看一下性能差距:
使用切片操作,在I5的苹果机上,每秒可以运行127万次。
使用split('_'),在I5的苹果机上,每秒可以运行90万次。
可以看出,简简单单换一个内置函数,换一点算法,就可以把效率提高40%以上!
测试代码如下:
#! /usr/bin/env python#coding=utf-8import times = '01_HX'#---------- test 1---------------start_time = time.time()print "start_time:", start_timej = 1while 1: j += 1 a = s[0:2] a2 = s[3:5] end_time = time.time() if end_time - start_time >= 1 : breakprint "loop_num:", jprint "end_time: ",end_timeprint a,a2#---------- test 2---------------start_time = time.time()print "start_time:", start_timej = 1while 1: j += 1 a = s.split('_') end_time = time.time() if end_time - start_time >= 1 : breakprint "loop_num:", jprint "end_time: ",end_timeprint a
测试结果如下:
start_time: 1362031838.14
loop_num: 1274972
end_time: 1362031839.15
01 HX
start_time: 1362031839.15
loop_num: 900801
end_time: 1362031840.16
['01', 'HX']
2, 用range()函数生成序列,与自定义序列
(1)a = range(0,6)
(2)a = [0, 1, 2, 3, 4, 5]
分别测试了一下,结果如下:
loop_num: 1029877
loop_num: 1602341
结论:还是自己显式定义序列,效率更高。
3, 生成一个序列的副本:用copy,与用切片特性
a = [0, 1, 2, 3, 4, 5]
(1)b = copy.copy(a)
(2)b = a[:]
分别测试了一下,结果如下:
loop_num: 677838
loop_num: 1530012
结论:变通的切片应用作为拷贝,比浅拷贝函数效率更高。注意,深拷贝效率很低!
while True 和 while 1
很多Python优化的文章,都会谈及这个。那么,到底能提高多少呢?我们来试试看:
import randomimport timestart_time = time.time() print start_time j = 1 while True: j += 1 end_time = time.time() if end_time - start_time >= 1 : break print j print end_timeprint "======== split =========="start_time = time.time() print start_time j = 1 while 1: j += 1 end_time = time.time() if end_time - start_time >= 1 : break print j print end_time
输出结果:
1399342863.16
2573550
1399342864.16
======== split ==========
1399342864.18
2973070
1399342865.18
一个是25万,一个是29万。大约提升了16%左右的性能。其实不是很明显。只是聊胜于无。
- python 之性能优化
- python 性能优化
- python性能优化摘录
- python性能优化
- Python性能优化指南
- Python性能优化
- python性能优化指南
- Python 性能优化
- Python性能优化指南
- python 性能优化篇
- python的性能优化
- Python 代码性能优化
- Python性能优化
- Python 性能优化
- Python代码性能优化
- python性能优化指南
- python性能优化
- python性能优化
- Silverlight CookiesHelper类
- Sicily 1344. 数列
- selenium试用
- jsp连接数据库的报错
- OFBiz 开发需要用到的几个重要(配置)文件
- python性能优化
- Address already in use: JVM_Bind<null>:8080
- 金蝶EAS BOS开发之扩展表应用
- 举例说明这些键的用法
- C++指针
- 详解EJB技术及实现原理
- C#调用SQL SERVER存储过程
- 给定一个数N,求出1-N之间的数字有多少个1,例如N=11时结果为4(只有1,10,11含1)
- MFC 如何添加自定义消息