parfor 减慢计算速度

parfor slows down computation

我运行这个代码在一台有44个工人的电脑上。但是,尽管整个循环的总执行时间下降了,但并行的每次迭代都比串行模式慢。

  template=cell(31,1);
  for i=1:31
     template{i}=rand(i+24);
  end
  parfor i=1:5
     img=rand(800,1280+i); % It's an other function that gives me the values of img ,here it's just an example
     tic
     cellfun (@(t) normxcorr2 ( t ,img),template,'UniformOutput',0);
     toc
  end

因此,每个循环的运行时间约为 18s。当我将 parfor 更改为 for 时,每个循环经过的时间约为 6.7 秒。

你能解释一下为什么在这种情况下 parfor 循环比 for 循环慢吗? 我检查了 MATLAB 文档和类似的问题,但它没有帮助我。

注意:parfor 版本的脚本执行总时间更快,我只是想了解为什么 cellfun 函数在并行版本中慢了 3 倍。

检查 CPU 用法。

我认为这里的主要原因是像 fft(很可能是 xcorr 的一部分)这样的东西已经使用了不止一个内核。我现在无法测试 parfor,但是普通的 for 循环在我的 4C/4T CPU 上使用您的代码已经有大约 70% CPU 的利用率。因此,parfor 最多只能填充剩余的 30%(在我的计算机上),但显然 运行 每个实例都会变慢。