简体   繁体   English

python multiprocessing同时处理数字数组

[英]python multiprocessing handling an array of numbers concurrently

I have a list of number: 我有一个号码清单:

a=[1,2,3,4,5,.....2000]

I have to square each number and update the same array, but instead of writing a loop i want to do it using parallel processing. 我必须对每个数字求平方并更新相同的数组,但我不想编写循环,而是想使用并行处理。

So squaring each number in the array becomes a process in itself. 因此,对数组中的每个数字进行平方运算本身就是一个过程。

Expected output=[1,3,9,16,25,........]

How can i achieve this with python multiprocessing library? 如何使用python多处理库实现此目的?

Already tried to Use threading library but the code is not fast enough, plus Threading library is not using all the cores. 已经尝试使用线程库,但是代码不够快,加上线程库没有使用所有内核。

You can use Pool class from the multiprocessing module 您可以从多处理模块中使用Pool

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    p = Pool(5)
    print(p.map(f, [1, 2, 3]))

#prints [1, 4, 9]

In this numpy would be handy because it works on Matrix methods to calculate. 在这种情况下,numpy会很方便,因为它适用于Matrix方法进行计算。 Here is the piece of code that can serve the purpose. 这是可以达到目的的代码。 In case you want to parallel it you can use the Pool function as stated 如果要并行处理,则可以使用上述Pool函数

import numpy as np
def Square(data):
    data_np = np.array(data) ** 2
    print (data_np)
Square([1, 2, 3])

You can try ProcessPoolExecutor in concurrent.futures module. 您可以在parallel.futures模块中尝试使用ProcessPoolExecutor Example code: 示例代码:

from time import time
from concurrent.futures import ProcessPoolExecutor


def gcd(pair):
    a, b = pair
    low = min(a, b)
    for i in range(low, 0, -1):
        if a % i == 0 and b % i == 0:
            return i


numbers = [(1963309, 2265973), (2030677, 3814172),
           (1551645,    2229620),   (2039045,   2020802)]
start = time()
results = list(map(gcd, numbers))
end = time()
print('1st Took %.3f seconds' % (end - start))
start = time()
pool = ProcessPoolExecutor(max_workers=2)
results = list(pool.map(gcd, numbers))
end = time()
print('2nd Took %.3f seconds' % (end - start))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM