MATLAB parfor 比 for 慢——有什么问题? [英] MATLAB parfor is slower than for -- what is wrong?

查看:131
本文介绍了MATLAB parfor 比 for 慢——有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的代码有如下循环:

the code I'm dealing with has loops like the following:

bistar = zeros(numdims,numcases); 
parfor hh=1:nt       
  bistar = bistar +  A(:,:,hh)*data(:,:,hh+1)' ;
end   

对于小 nt (10).

for small nt (10).

计时后,它实际上比使用常规循环慢 100 倍!!!我知道 parfor 可以进行并行求和,所以我不确定为什么这不起作用.

After timing it, it is actually 100 times slower than using the regular loop!!! I know that parfor can do parallel sums, so I'm not sure why this isn't working.

我跑

matlabpool

在运行我的代码之前使用开箱即用的配置.

with the out-of-the-box configurations before running my code.

我对 matlab 比较陌生,刚开始使用并行功能,所以请不要假设我没有做蠢事.

I'm relatively new to matlab, and just started to use the parallel features, so please don't assume that I'm am not doing something stupid.

谢谢!

PS:我在四核上运行代码,所以我希望看到一些改进.

PS: I'm running the code on a quad core so I would expect to see some improvements.

推荐答案

对于 nt 的小值,对结果进行分区和分组(划分工作和从多个线程/核心收集结果的开销)很高.这是正常的,您不会为可以在简单循环中快速执行的简单任务划分数据.

Making the partitioning and grouping the results (overhead in dividing the work and gathering results from the several threads/cores) is high for small values of nt. This is normal, you would not partition data for easy tasks that can be performed quickly in a simple loop.

总是在循环内执行一些值得分区开销的具有挑战性的事情.这是一篇不错的并行编程简介.

Always perform something challenging inside the loop that is worth the partitioning overhead. Here is a nice introduction to parallel programming.

线程来自线程池,因此不应存在创建线程的开销.但是为了从 bistar 大小创建部分结果 n 矩阵,必须创建所有部分结果,然后必须添加所有这些部分结果(重新组合).在直线循环中,这很有可能就地完成,不会发生分配.

The threads come from a thread pool so the overhead of creating the threads should not be there. But in order to create the partial results n matrices from the bistar size must be created, all the partial results computed and then all these partial results have to be added (recombining). In a straight loop, this is with a high probability done in-place, no allocations take place.

帮助中的完整声明(感谢您提供以下链接)是:

The complete statement in the help (thanks for your link hereunder) is:

如果计算 f、g 和 h 的时间是大,parfor 将显着比对应的更快陈述,即使 n 是相对的小.

If the time to compute f, g, and h is large, parfor will be significantly faster than the corresponding for statement, even if n is relatively small.

所以你看到它们的意思和我的意思完全一样,只有当你在循环中做的事情足够复杂/耗时,小 n 值的开销才值得付出努力.

So you see they mean exactly the same as what I mean, the overhead for small n values is only worth the effort if what you do in the loop is complex/time consuming enough.

这篇关于MATLAB parfor 比 for 慢——有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆