假设你在 python 中有一个列表理解,比如
Values = [ f(x) for x in range( 0, 1000 ) ]
f 只是一个没有副作用的函数。因此所有条目都可以独立计算。
与“显而易见的”实现相比,Python 是否能够提高此列表理解的性能?例如通过多核 CPU 上的共享内存并行化?
最佳答案
在 Python 3.2 中,他们添加了 concurrent.futures
,一个很好的同时解决问题的库。考虑这个例子:
import math, time
from concurrent import futures
PRIMES = [112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419, 112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def bench(f):
start = time.time()
f()
elapsed = time.time() - start
print("Completed in {} seconds".format(elapsed))
def concurrent():
with futures.ProcessPoolExecutor() as executor:
values = list(executor.map(is_prime, PRIMES))
def listcomp():
values = [is_prime(x) for x in PRIMES]
我的四核结果:
>>> bench(listcomp)
Completed in 14.463825941085815 seconds
>>> bench(concurrent)
Completed in 3.818351984024048 seconds
关于Python 和列表理解的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6214091/