不久前,我提供了这个问题的答案。
目标:计算此矩阵中[3 6]
范围内的值的数量:
A = [2 3 4 5 6 7;
7 6 5 4 3 2]
我想出了 12 种不同的方法来做到这一点:
count = numel(A( A(:)>3 & A(:)<6 )) %# (1)
count = length(A( A(:)>3 & A(:)<6 )) %# (2)
count = nnz( A(:)>3 & A(:)<6 ) %# (3)
count = sum( A(:)>3 & A(:)<6 ) %# (4)
Ac = A(:);
count = numel(A( Ac>3 & Ac<6 )) %# (5,6,7,8)
%# prevents double expansion
%# similar for length(), nnz(), sum(),
%# in the same order as (1)-(4)
count = numel(A( abs(A-(6+3)/2)<3/2 )) %# (9,10,11,12)
%# prevents double comparison and &
%# similar for length(), nnz(), sum()
%# in the same order as (1)-(4)
所以,我决定找出哪个最快。测试代码:
A = randi(10, 50);
tic
for ii = 1:1e5
%# method is inserted here
end
toc
结果(最好的 5 次运行,均以秒为单位):
%# ( 1): 2.981446
%# ( 2): 3.006602
%# ( 3): 3.077083
%# ( 4): 2.619057
%# ( 5): 3.011029
%# ( 6): 2.868021
%# ( 7): 3.149641
%# ( 8): 2.457988
%# ( 9): 1.675575
%# (10): 1.675384
%# (11): 2.442607
%# (12): 1.222510
所以这似乎count = sum(( abs(A(:)-(6+3)/2) < (3/2) ));
是去这里最快的方式......
我<
用两个部门交易一个,一个加法和一个abs
,执行时间不到一半!有没有人解释为什么会这样?
JIT 编译器可能会用内存中的单个值替换除法/加法,但仍然存在abs
...Branch 错误预测?像这样简单的事情似乎很愚蠢......