Python与列表理解的性能
假设您有python中的列表理解,如Python与列表理解的性能,python,performance,list-comprehension,Python,Performance,List Comprehension,假设您有python中的列表理解,如 Values = [ f(x) for x in range( 0, 1000 ) ] f只是一个没有副作用的函数。因此,所有条目都可以独立计算 与“明显的”实现相比,Python是否能够提高此列表理解的性能;e、 通过在多核CPU上共享内存并行化?不,Python不会神奇地为您并行化。事实上,它不能,因为它不能证明条目的独立性;这将需要大量的程序检查/验证,这在一般情况下是不可能正确的 如果您想要快速粗粒度多核并行,我建议您: 我不仅看到了使用这个库的近
Values = [ f(x) for x in range( 0, 1000 ) ]
f只是一个没有副作用的函数。因此,所有条目都可以独立计算
与“明显的”实现相比,Python是否能够提高此列表理解的性能;e、 通过在多核CPU上共享内存并行化?不,Python不会神奇地为您并行化。事实上,它不能,因为它不能证明条目的独立性;这将需要大量的程序检查/验证,这在一般情况下是不可能正确的 如果您想要快速粗粒度多核并行,我建议您: 我不仅看到了使用这个库的近似线性加速,它还具有信号的伟大特性,例如从Ctrl-C到其工作进程的信号,这不是所有多进程库都能做到的
请注意,joblib并不真正支持共享内存并行性:它生成工作进程,而不是线程,因此它会在向工作进程发送数据和将结果返回主进程时产生一些通信开销。如果以下速度更快,请尝试:
Values = map(f,range(0,1000))
这是一种函数式的编码方式
另一个想法是用生成器表达式替换代码中出现的所有值
imap(f,range(0,1000)) # Python < 3
map(f,range(0,1000)) # Python 3
imap(f,范围(01000))#Python<3
地图(f,范围(01000))#Python 3
在Python3.2中,他们添加了一个很好的库,可以同时解决问题。考虑这个例子:
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可以,但在一个类似的问题中还有更多的信息。您可能希望为“bench”函数使用decorator,因为它实际上已经是一个decorator了。
>>> bench(listcomp)
Completed in 14.463825941085815 seconds
>>> bench(concurrent)
Completed in 3.818351984024048 seconds