转载请注明作者和出处: http://blog.csdn.net/john_bh/
文章目录
python 使用 concurrent.futures 并行处理数据,速度提高 2~6 倍。对比代码如下:
1. 避免全局变量
许多人刚开始会用 Python 语言写一些简单的脚本,当编写脚本时,通常习惯了直接将其写为全局变量。但是,由于全局变量和局部变量实现方式不同,定义在全局范围内的代码运行速度会比定义在函数中的慢不少。通过将脚本语句放入到函数中,通常可带来 15% - 30% 的速度提升。如下面对比代码:
# -*- coding :utf-8 -*-
import math
import time
start=time.time()
size = 100000
for x in range(size):
for y in range(size):
z = math.sqrt(x) + math.sqrt(y)
print("Global Taken Time: {}".format(time.time()-start))
def main(): # 定义到函数中,以减少全部变量使用
start = time.time()
size = 100000
for x in range(size):
for y in range(size):
z = math.sqrt(x) + math.sqrt(y)
print("Local Taken Time: {}".format(time.time() - start))
main()
Global Taken Time: 30.072156190872192
Local Taken Time: 24.563132286071777
2. 避免使用 .
2.1 避免模块和函数属性访问
每次使用.(属性访问操作符时)会触发特定的方法,如__getattribute__()
和__getattr__()
,这些方法会进行字典操作,因此会带来额外的时间开销。通过from import语句,可以消除属性访问
。
下面代码经过三步优化:
- 第一步优化:使用
from math import sqrt
替换import math
,避免math.sqrt的使用; - 第二部优化:将在局部函数中使用
sqrt = math.sqrt
赋值给局部变量,进行局部化处理; - 第三步优化:优化函数中调用 list 的
append
方法。通过将该方法赋值给一个局部变量,可以彻底消除函数中for循环内部的.
使用。
代码实现以及运行效率如下:
# -*- coding :utf-8 -*-
import math
import time
def computeSqrt1(size: int):
"""
不推荐写法
"""
result = []
for i in range(size):
result.append(math.sqrt(i))
return result
from math import sqrt
def computeSqrt2(size: int):
"""
优化了1.from math import sqrt,避免math.sqrt的使用
"""
result = []
for i in range(size):
result.append(sqrt(i)) # 避免math.sqrt的使用
return result
def computeSqrt3(size: int):
"""
优化了1.from math import sqrt,避免math.sqrt的使用
2.sqrt = math.sqrt 赋值给局部变量
"""
result = []
sqrt = math.sqrt # 赋值给局部变量
for i in range(size):
result.append(sqrt(i)) # 避免math.sqrt的使用
return result
def computeSqrt4(size: int):
"""
优化了1.from math import sqrt,避免math.sqrt的使用
2.sqrt = math.sqrt 赋值给局部变量
3.result.append(sqrt(i))优化为 append = result.append,append(sqrt(i)) 避免 result.append 和 math.sqrt 的使用
"""
result = []
append = result.append
sqrt = math.sqrt # 赋值给局部变量
for i in range(size):
append(sqrt(i)) # 避免 result.append 和 math.sqrt 的使用
return result
def test(computeSqrt_fun):
size = 10000
start=time.time()
for _ in range(size):
result = computeSqrt_fun(size)
takenTime=time.time() - start
print("{} Taken Time: {}".format(computeSqrt_fun.__name__,takenTime))
if __name__ == "__main__":
test(computeSqrt1)
test(computeSqrt2)
test(computeSqrt3)
test(computeSqrt4)
computeSqrt1 Taken Time: 20.50309944152832
computeSqrt2 Taken Time: 13.954072952270508
computeSqrt3 Taken Time: 13.141065120697021
computeSqrt4 Taken Time: 11.455055952072144
2.2 避免类内属性访问
避免 .
的原则也适用于类内属性,访问self._value
的速度会比访问一个局部变量更慢一些。通过将需要频繁访问的类内属性赋值给一个局部变量,可以提升代码运行速度。对比代码如下所示:
# -*- coding :utf-8 -*-
import math
import time
from typing import List
class DemoClass:
def __init__(self, value: int):
self._value = value
def computeSqrt1(self, size: int) -> List[float]: # 不推荐
result = []
append = result.append
sqrt = math.sqrt
for _ in range(size):
append(sqrt(self._value))
return result
def computeSqrt2(self, size: int) -> List[float]:
result = []
append = result.append
sqrt = math.sqrt
value = self._value # 避免 self._value 的使用
for _ in range(size):
append(sqrt(value)) # 避免 self._value 的使用
return result
def test():
size = 10000
start1 = time.time()
for _ in range(size):
demo_instance = DemoClass(size)
result = demo_instance.computeSqrt1(size)
takenTime1 = time.time() - start1
print("computeSqrt1 Taken Time: {}".format(takenTime1))
start2 = time.time()
for _ in range(size):
demo_instance = DemoClass(size)
result = demo_instance.computeSqrt2(size)
takenTime2=time.time() - start2
print("computeSqrt2 Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
test()
computeSqrt1 Taken Time: 13.82009768486023
computeSqrt2 Taken Time: 11.740054607391357
3. 避免不必要的抽象
任何时候当你使用额外的处理层(比如装饰器、属性访问、描述器)去包装代码时,都会让代码变慢。大部分情况下,需要重新进行审视使用属性访问器的定义是否有必要,使用getter/setter函数对属性进行访问通常是 C/C++ 程序员遗留下来的代码风格。如果真的没有必要,就使用简单属性。对比代码如下:
# -*- coding :utf-8 -*-
import time
class DemoClass1:
"""
不推荐使用
"""
def __init__(self, value: int):
self.value = value
@property
def value(self) -> int:
return self._value
@value.setter
def value(self, x: int):
self._value = x
class DemoClass2:
"""
优化后,避免不必要的抽象
"""
def __init__(self, value: int):
self.value = value # 避免不必要的属性访问器
def test():
size = 1000000
start1 = time.time()
for i in range(size):
demo_instance = DemoClass1(size)
value = demo_instance.value
demo_instance.value = i
takenTime1 = time.time() - start1
print("DemoClass1 Taken Time: {}".format(takenTime1))
start2 = time.time()
for i in range(size):
demo_instance = DemoClass2(size)
value = demo_instance.value
demo_instance.value = i
takenTime2 = time.time() - start2
print("DemoClass2 Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
test()
DemoClass1 Taken Time: 0.6100289821624756
DemoClass2 Taken Time: 0.3529999256134033
4. 避免数据复制
4.1 避免无意义的数据复制
对比代码如下:
# -*- coding :utf-8 -*-
import time
def fun1():
"""
不推荐
"""
size = 10000
start1 = time.time()
for _ in range(size):
value = range(size)
value_list = [x for x in value]
square_list = [x * x for x in value_list]
takenTime1 = time.time() - start1
print("fun1 Taken Time: {}".format(takenTime1))
def fun2():
size = 10000
start2 = time.time()
for _ in range(size):
value = range(size)
square_list = [x * x for x in value] # 避免无意义的复制
takenTime2 = time.time() - start2
print("fun2 Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
fun1()
fun2()
fun1 Taken Time: 7.48906683921814
fun2 Taken Time: 5.61405348777771
另外一种情况是对 Python 的数据共享机制过于偏执,并没有很好地理解或信任 Python 的内存模型,滥用 copy.deepcopy()
之类的函数。通常在这些代码中是可以去掉复制操作的。
4.2 交换值时不使用中间变量
交换值时创建了一个临时变量temp,如果不借助中间变量,代码更为简洁、且运行速度更快。
# -*- coding :utf-8 -*-
import time
def fun1():
"""
不推荐
"""
size = 1000000
start1 = time.time()
for _ in range(size):
a = 3
b = 5
temp = a
a = b
b = temp
takenTime1 = time.time() - start1
print("fun1 Taken Time: {}".format(takenTime1))
def fun2():
size = 1000000
start2 = time.time()
for _ in range(size):
a = 3
b = 5
a, b = b, a # 不借助中间变量
takenTime2 = time.time() - start2
print("fun2 Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
fun1()
fun2()
fun1 Taken Time: 0.04600167274475098
fun2 Taken Time: 0.0330042839050293
4.3 字符串拼接用 join
而不是 +
当使用 a + b
拼接字符串时,由于 Python 中字符串是不可变对象,其会申请一块内存空间,将a和b分别复制到该新申请的内存空间中
。因此,如果要拼接
n
n
n 个字符串,会产生
n
−
1
n-1
n−1 个中间结果,每产生一个中间结果都需要申请和复制一次内存,严重影响运行效率。而使用join()
拼接字符串时,会首先计算出需要申请的总的内存空间,然后一次性地申请所需内存,并将每个字符串元素复制到该内存中去。
# -*- coding :utf-8 -*-
import time
import string
from typing import List
def concatString1(string_list: List[str]) -> str:
"""
不推荐
"""
result = ''
for str_i in string_list:
result += str_i
return result
def concatString2(string_list: List[str]) -> str:
return ''.join(string_list) # 使用 join 而不是 +
def test():
string_list = list(string.ascii_letters * 100)
start1 = time.time()
for _ in range(10000):
result = concatString1(string_list)
takenTime1 = time.time() - start1
print("concatString1 by + Taken Time: {}".format(takenTime1))
start2 = time.time()
for _ in range(10000):
result = concatString2(string_list)
takenTime2 = time.time() - start2
print("concatString2 by join Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
test()
concatString1 by + Taken Time: 9.188046216964722
concatString2 by join Taken Time: 0.3179972171783447
5. 利用if
条件的短路特性
if
条件的短路特性是指对if a and b
这样的语句, 当a
为False
时将直接返回,不再计算b
;对于if a or b
这样的语句,当a
为True
时将直接返回,不再计算b
。因此, 为了节约运行时间,对于or
语句,应该将值为True
可能性比较高的变量写在or
前,而and
应该推后。
# -*- coding :utf-8 -*-
import time
import string
from typing import List
def concatString1(string_list: List[str]) -> str:
abbreviations = {'cf.', 'e.g.', 'ex.', 'etc.', 'flg.', 'i.e.', 'Mr.', 'vs.'}
result = ''
for str_i in string_list:
if str_i in abbreviations:
result += str_i
return result
def concatString2(string_list: List[str]) -> str:
abbreviations = {'cf.', 'e.g.', 'ex.', 'etc.', 'flg.', 'i.e.', 'Mr.', 'vs.'}
result = ''
for str_i in string_list:
if str_i[-1] == '.' and str_i in abbreviations: # 利用 if 条件的短路特性
result += str_i
return result
def test():
string_list = ['Mr.', 'Hat', 'is', 'Chasing', 'the', 'black', 'cat', '.']
start1 = time.time()
for _ in range(100000):
result = concatString1(string_list)
takenTime1 = time.time() - start1
print("concatString1 Taken Time: {}".format(takenTime1))
start2 = time.time()
for _ in range(100000):
result = concatString2(string_list)
takenTime2 = time.time() - start2
print("concatString2 Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
test()
理论上应该concatString2 比concatString1 快,但是结果是:
concatString1 Taken Time: 0.051025390625
concatString2 Taken Time: 0.07299995422363281
6. 循环优化
6.1 用for
循环代替while
循环,使用隐式for
循环代替显式for
循环
# -*- coding :utf-8 -*-
import time
def computeSum_while(size: int) -> int:
"""
不推荐
"""
sum_ = 0
i = 0
while i < size:
sum_ += i
i += 1
return sum_
def computeSum_for(size: int) -> int:
sum_ = 0
for i in range(size): # for 循环代替 while 循环
sum_ += i
return sum_
def computeSum(size: int) -> int:
return sum(range(size)) # 隐式 for 循环代替显式 for 循环
def test():
size = 10000
start1 = time.time()
for _ in range(size):
sum_ = computeSum_while(size)
takenTime1 = time.time() - start1
print("computeSum_while Taken Time: {}".format(takenTime1))
start2 = time.time()
for _ in range(size):
sum_ = computeSum_for(size)
takenTime2 = time.time() - start2
print("computeSum_for Taken Time: {}".format(takenTime2))
start3 = time.time()
for _ in range(size):
sum_ = computeSum(size)
takenTime3 = time.time() - start3
print("computeSum Taken Time: {}".format(takenTime3))
if __name__ == "__main__":
test()
computeSum_while Taken Time: 8.544030666351318
computeSum_for Taken Time: 4.945058107376099
computeSum Taken Time: 1.5659689903259277
6.2 减少内层for循环的计算
代码中尽量少用内循环,如下面函数 for_in 中 sqrt(x)
位于内侧for
循环, 每次训练过程中都会重新计算一次,增加了时间开销。
# -*- coding :utf-8 -*-
import time
import math
def for_in():
"""
不推荐
"""
start1 = time.time()
size = 10000
sqrt = math.sqrt
for x in range(size):
for y in range(size):
z = sqrt(x) + sqrt(y)
takenTime1 = time.time() - start1
print("for_in Taken Time: {}".format(takenTime1))
def for_out():
size = 10000
sqrt = math.sqrt
start2 = time.time()
for x in range(size):
sqrt_x = sqrt(x) # 减少内层 for 循环的计算
for y in range(size):
z = sqrt_x + sqrt(y)
takenTime2 = time.time() - start2
print("for_out Taken Time: {}".format(takenTime2))
if __name__ == "__main__":
for_in()
for_out()
for_in Taken Time: 19.739089250564575
for_out Taken Time: 11.243038654327393
7. 使用numba.jit
numba可以将 Python 函数 JIT 编译为机器码执行,大大提高代码运行速度。关于numba的更多信息见下面的主页:http://numba.pydata.org/
# -*- coding :utf-8 -*-
import time
import numba
ef computeSum_while(size: int) -> int:
"""
不推荐
"""
sum_ = 0
i = 0
while i < size:
sum_ += i
i += 1
return sum_
def computeSum_for(size: int) -> int:
sum_ = 0
for i in range(size): # for 循环代替 while 循环
sum_ += i
return sum_
def computeSum(size: int) -> int:
return sum(range(size)) # 隐式 for 循环代替显式 for 循环
@numba.jit
def computeSum_jit(size: float) -> int:
sum = 0
for i in range(size):
sum += i
return sum
def test():
size = 10000
start1 = time.time()
for _ in range(size):
sum_ = computeSum_while(size)
takenTime1 = time.time() - start1
print("computeSum_while Taken Time: {}".format(takenTime1))
start2 = time.time()
for _ in range(size):
sum_ = computeSum_for(size)
takenTime2 = time.time() - start2
print("computeSum_for Taken Time: {}".format(takenTime2))
start3 = time.time()
for _ in range(size):
sum_ = computeSum(size)
takenTime3 = time.time() - start3
print("computeSum Taken Time: {}".format(takenTime3))
start4 = time.time()
for _ in range(size):
sum_ = computeSum_jit(size)
takenTime4 = time.time() - start4
print("computeSum_jit Taken Time: {}".format(takenTime4))
if __name__ == "__main__":
test()
computeSum_while Taken Time: 8.01906418800354
computeSum_for Taken Time: 4.3460166454315186
computeSum Taken Time: 1.5610063076019287
computeSum_jit Taken Time: 0.4790055751800537
8. 选择合适的数据结构
Python 内置的数据结构如str, tuple, list, set, dict
底层都是 C 实现的,速度非常快,自己实现新的数据结构想在性能上达到内置的速度几乎是不可能的。
list
类似于 C++ 中的std::vector
,是一种动态数组。其会预分配一定内存空间,当预分配的内存空间用完,又继续向其中添加元素时,会申请一块更大的内存空间,然后将原有的所有元素都复制过去,之后销毁之前的内存空间,再插入新元素。删除元素时操作类似,当已使用内存空间比预分配内存空间的一半还少时,会另外申请一块小内存,做一次元素复制,之后销毁原有大内存空间。因此,如果有频繁的新增、删除操作,新增、删除的元素数量又很多时,list
的效率不高。此时,应该考虑使用 collections.deque
。collections.deque是双端队列
,同时具备栈和队列的特性,能够在两端进行
O
(
1
)
O(1)
O(1) 复杂度的插入和删除操作。
list
的查找操作也非常耗时。当需要在list
频繁查找某些元素,或频繁有序访问这些元素时,可以使用bisect
维护list
对象有序并在其中进行二分查找,提升查找的效率。
另外一个常见需求是查找极小值或极大值,此时可以使用heapq模块
将list
转化为一个堆,使得获取最小值的时间复杂度是
O
(
1
)
O(1)
O(1) 。
下面的网页给出了常用的 Python 数据结构的各项操作的时间复杂度:https://wiki.python.org/moin/TimeComplexity 。
- list 操作:
- deque操作:
- set操作:
- dict操作:
参考文章:
- Python加速运行技巧
- David Beazley & Brian K. Jones. Python Cookbook, Third edition. O’Reilly Media, ISBN: 9781449340377, 2013
- 张颖 & 赖勇浩. 编写高质量代码:改善Python程序的91个建议. 机械工业出版社, ISBN: 9787111467045, 2014.
- 常用的 Python 数据结构的各项操作的时间复杂度
- numba 主页