You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对示例代码实现多核并行计算?

Python实现类似Mathematica ParallelTable的并行计算

你的场景中,每个y[i] = x² * a[i]的计算完全独立,非常适合拆分到多核并行处理。以下是几种Python中的实现方案:

方法1:使用concurrent.futures.ProcessPoolExecutor

这是Python标准库中最简洁的并行实现方式,用法接近Mathematica的ParallelTable:

import concurrent.futures

def calculate_y_element(a_i, x):
    return x ** 2 * a_i

if __name__ == "__main__":
    a = [3.5, 7.6, 8.6, 1.3]
    x = 12
    
    # 初始化进程池,默认自动匹配CPU核心数
    with concurrent.futures.ProcessPoolExecutor() as executor:
        # map方法会按输入顺序返回结果,和ParallelTable逻辑一致
        y = list(executor.map(calculate_y_element, a, [x]*len(a)))
    
    # 输出结果
    for y_i, a_i in zip(y, a):
        print(y_i, a_i)

方法2:使用multiprocessing.Pool

这是更底层的进程池实现,灵活性更高:

from multiprocessing import Pool

def calculate_y_element(a_i, x):
    return x ** 2 * a_i

if __name__ == "__main__":
    a = [3.5, 7.6, 8.6, 1.3]
    x = 12
    
    with Pool() as pool:
        # starmap支持直接传入多参数的迭代器
        y = pool.starmap(calculate_y_element, [(elem, x) for elem in a])
    
    # 输出结果
    for y_i, a_i in zip(y, a):
        print(y_i, a_i)

方法3:numpy向量化(多线程并行)

如果只是简单数值计算,numpy的向量化操作会自动利用多线程(依赖BLAS/LAPACK库),代码更简洁:

import numpy as np

a = np.array([3.5, 7.6, 8.6, 1.3])
x = 12
y = (x ** 2) * a

# 输出结果
for y_i, a_i in zip(y, a):
    print(y_i, a_i)

注意事项

  • 必须添加if __name__ == "__main__":Windows系统下子进程会重新导入主模块,不加会导致无限创建进程;Linux/macOS虽无此问题,但添加后可保证跨平台兼容性。
  • 进程池的大小:默认会使用全部CPU核心,也可以通过ProcessPoolExecutor(max_workers=N)或Pool(N)指定核心数。

内容的提问来源于stack exchange,提问作者Mam Mam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 11:55:38