gpt4 book ai didi

multithreading - 在matlab中,parfor的替代方案不太严格?

转载 作者:行者123 更新时间:2023-12-03 13:20:37 27 4
gpt4 key购买 nike

我的代码在结构上类似于Matlab中的以下代码:

bestConfiguration = 0;
bestConfAwesomeness = 0;

for i=1:X
% note that providing bestConfAwesomeness to the function helps it stop if it sees the current configuration is getting hopeless anyway
[configuration, awesomeness] = expensive_function(i, bestConfAwesomeness);
if awesomeness > bestConfAwesomeness
bestConfAwesomeness = awesomeness;
bestConfiguration = configuration;
end
end

还有更多内容,但基本结构如上所述。 X可能会变得非常大。我正在尝试使此代码并行运行,因为 expensive_function()需要很长时间才能运行。

问题是Matlab不允许我只将 for更改为 parfor,因为它不喜欢我在循环中更新最佳配置。

到目前为止,我所做的是:
[allConfigurations, allAwesomeness] = deal(cell(1, X));

parfor i=1:X
% note that this is not ideal because I am forced to use 0 as the best awesomeness in all cases
[allConfigurations{i}, allAwesomeness{i}] = expensive_function(i, 0);
end

for i=1:X
configuration = allConfigurations{i};
awesomeness = allAwesomeness{i};
if awesomeness > bestConfAwesomeness
bestConfAwesomeness = awesomeness;
bestConfiguration = configuration;
end
endfor

就运行时间而言,这更好。但是,对于大的输入,由于所有配置总是被保存,因此会占用大量的内存。另一个问题是,即使可能知道更好的配置,使用 parfor也会强制我始终将 0提供为最佳配置。

Matlab是否提供更好的方法来做到这一点?

基本上,如果我不必使用Matlab并可以自己管理线程,那么我将有一个中央线程向工作人员提供工作(即让他们运行 expensive_function(i)),一旦工作人员返回,请查看它产生的数据并将其与到目前为止找到的最好的进行比较,并进行相应的更新。无需保存所有配置,这似乎是使 parfor工作的唯一方法。

有没有办法在Matlab中完成上述操作?

最佳答案

每次在循环中使用bestConfAwesomeness意味着循环的迭代与顺序无关,因此PARFOR为什么不满意。您可以采用的一种方法是使用SPMD,并让每个工作人员并行执行expensiveFunction,然后进行通信以更新bestConfAwesomeness。像这样的东西:

bestConfiguration = 0;
bestConfAwesomeness = 0;
spmd
for idx = 1:ceil(X/numlabs)
myIdx = labindex + ((idx-1) * numlabs);
% should really guard against myIdx > X here.
[thisConf, thisAwesome] = expensiveFunction(myIdx, bestConfAwesomeness);
% Now, we must communicate to see if who is best
[bestConfiguration, bestAwesomeness] = reduceAwesomeness(...
bestConfiguration, bestConfAwesomeness, thisConf, thisAwesome);
end
end

function [bestConf, bestConfAwesome] = reduceAwesomeness(...
bestConf, bestConfAwesome, thisConf, thisAwesome)
% slightly lazy way of doing this, could be optimized
% but probably not worth it if conf & awesome both scalars.
allConfs = gcat(bestConf);
allAwesome = gcat(thisAwesome);
[maxThisTime, maxLoc] = max(allAwesome);
if maxThisTime > bestConfAwesome
bestConfAwesome = maxThisTime;
bestConf = allConfs(maxLoc);
end
end

关于multithreading - 在matlab中,parfor的替代方案不太严格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16330919/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com