[英]How to find the maximum value of a list in parallel?
我正在使用一个函数,该函数采用值组合并更新计算值。 如果我将几个组合传递给 function,它将计算几个不同的值,我想保留所有这些值的最大值。 为了加快进程,我正在并行运行它。
简化,我有一个 function,它采用当前最大值并更新它(如果需要),给出一个列表。 如何并行运行此 function 以加快计算速度,与所有活动进程共享值,以使当前值始终为最大值? 最后,我想知道组合列表中的组合/列表会给我带来最大值。
在这个使用多处理模块的示例中,脚本应该返回 62(最大值),而有时它会返回 45。这里发生了什么,我需要更改什么?
from multiprocessing import Value, Process
import time
def update_best(numbers, best):
for n in numbers:
time.sleep(.1) # working ...
if n > best.value:
best.value = n
nos = [[1.1,2.1,3.1], [62,5.2,4.2], [7.3,8.3,9.3], [3.4,4.4,5.4], [45,4.5,3.5]]
for combo in nos:
best = Value('f', .42)
p1 = Process(target=update_best, args=(combo,best,))
p2 = Process(target=update_best, args=(combo,best,))
p1.start()
p2.start()
print("end")
time.sleep(3)
print(f"best = {best.value}")
编辑:非并行版本如下所示:
def update_best(numbers):
global best
for n in numbers:
time.sleep(.1)
if n > best:
best = n
nos = [[1.1,2.1,3.1], [62,5.2,4.2], [7.3,8.3,9.3], [3.4,4.4,5.4], [45,4.5,3.5]]
best = .42
for combo in nos:
update_best(combo)
print("end")
time.sleep(3)
print(f"best = {best}")
它实际上并不复杂。 我建议使用multiprocessing.Pool
及其 function map
。 像这样:
import os
import multiprocessing as mp
def partition(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def mymax(vals):
print(os.getpid(), vals)
return max(vals)
def pmax(vals):
with mp.Pool(5) as pool:
results = pool.map(mymax, partition(vals, 5))
return max(results)
if __name__ == "__main__":
m = pmax([1.1,2.1,3.1, 62,5.2,4.2, 7.3,8.3,9.3, 3.4,4.4,5.4, 45,4.5,3.5])
print(m)
Output:
$ python3 pmax.py
829763 [1.1, 2.1, 3.1, 62, 5.2]
829764 [4.2, 7.3, 8.3, 9.3, 3.4]
829765 [4.4, 5.4, 45, 4.5, 3.5]
62
重要提示:您必须在主文件中使用if __name__ == "__main__":
否则它将无法正常工作。
解释:
除非您使用一些 IPC 原语(共享 memory、消息队列等),否则您不能与不同的进程共享变量。
但是,您可以对问题应用分而治之,并分两个阶段解决:
The Python for loop can be used to find the max value in a list by comparing each value in the array and storing the largest value in a variable.
For example, let’s declare an array of random integers and print out the max value. Also, declare a variable max_value to store the maximum value and print it out after the loop is finished.
numbers = [55, 4, 92, 1, 104, 64, 73, 99, 20]
max_value = None
for num in numbers:
if (max_value is None or num > max_value):
max_value = num
print('Maximum value:', max_value)
Output:
Maximum value: 104
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.