matlab parfor issues

When parallelizing my optimization code using parfor, there are notable differences from the serial "for" loop. Digging into the internet, I found two possible cause causes. 

Intel MKL

My optimization involves matrix manipulations (inverse, multiplicaiton, etc), which relies on the Intel MKL. It seems to be an know issue that mkl produces different results depending on the number of threads involved.

Matlab quirks

Refer to this blog.

For me, the speed/precision tradeoff is not worth it atm. I'll see what can be done.

### MATLAB `parfor` 并行循环语法详解 #### 一、基础语法 `parfor` 是用于执行并行计算的循环结构,在多核处理器或多台计算机上加速代码运行。其基本形式如下: ```matlab parfor i = istart:istep:iend % 循环体内的命令序列 end ``` 其中,`i` 表示循环变量;`istart`, `istep`, 和 `iend` 定义了迭代范围[^1]。 #### 二、注意事项 - **初始化开销**:首次使用 `parfor` 可能会有额外延迟来启动必要的资源分配过程。因此建议在同一会话中重复利用已建立的工作池以减少等待时间[^2]。 - **依赖关系处理**:为了确保线程安全性和正确性,应避免在不同迭代之间存在相互依存的数据访问模式。具体来说就是防止出现读取未赋值或正在被其他 worker 修改中的共享内存区域的情况。 #### 三、简单例子展示如何运用 `parfor` 下面给出一段简单的代码片段用来对比串行版本 (`for`) 和并行化后的版本(`parfor`) 的性能差异: ```matlab % 创建一个较大的数组作为测试对象 A = rand(1000, 1000); tic; % 开始计时 B_for = zeros(size(A)); for rowIdx = 1:size(A, 1) B_for(rowIdx,:) = A(rowIdx,:).^2; end timeForLoop = toc; % 结束计时并记录耗时 tic; % 再次开始新的计时周期 C_parfor = zeros(size(A)); parfor colIdx = 1:size(A, 2) C_parfor(:,colIdx) = A(:,colIdx).^2; end timeParforLoop = toc; % 记录此次结束时刻距离上次 tic 所经过秒数 disp(['Time taken by for loop is ', num2str(timeForLoop), ' seconds']); disp(['Time taken by parfor loop is ', num2str(timeParforLoop), ' seconds']); ``` 这段脚本创建了一个大矩阵,并分别用常规 `for` 循环和 `parfor` 来对其元素平方运算。最后打印两者所需的时间以便比较效率提升情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值