本文介绍了MATLAB是否执行公共子表达式消除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MATLAB的优化器是否对MATLAB代码执行通用的子表达式消除?例如:
Does MATLAB's optimizer perform common subexpression elimination on MATLAB code? For example:
if max(val) > minVal && max(val) < maxVal
maxVal = max(val)
end
max(val)
在那里多久被评估一次?将中间值存储在一个临时变量中是否有意义(假设重复计算很昂贵),或者MATLAB是否会自动处理呢?
How often is max(val)
evaluated there? Does it make sense to store the intermediate value in a temporary variable (assuming the repeated calculation is expensive) or does MATLAB handle this automatically?
推荐答案
很肯定,对于子表达式消除,答案是否",对于存储中间值,答案是是".示例:
Pretty sure the answer is no to subexpression elimination and yes to storing intermediate values. Example:
>> x = rand(10000, 1);
>> tic;
for i = 1:100000
y = max(x) + max(x);
end
toc;
Elapsed time is 4.297135 seconds.
>> tic;
for i = 1:100000
m = max(x);
y = m + m;
end
toc;
Elapsed time is 1.074672 seconds.
即使是+之类的内置操作,似乎也没有得到优化.类似的测试表明
Even built-in operations like + don't seem to be optimised; a similar test showed that
z = (x + x);
y = z + z + z;
比以下速度快:
y = (x + x) + (x + x) + (x + x);
这篇关于MATLAB是否执行公共子表达式消除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!