Python 和列表理解的性能

标签 python performance list-comprehension

假设你在 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/

相关文章:

python - 在 Python 中递归遍历字典?

python - 如何将具有多个行标题的 Excel 数据插入到 pandas 数据框中

python - 如何用 pandas 列制作出现矩阵

python - 导入错误 : No module named ***** in python

c++ - 这些函数中哪个运行得更快?

python - 在 Python 列表推导式中插入 tkinter 进度条

python - 在 Python 脚本末尾生成 pcap 文件

mysql全文索引性能问题

html - 每个 angular2 组件的单独 CSS 文件会影响页面性能吗?

python使用列表理解对dict的多级列表进行切片