我正在进行3种方法的比较和性能测试,以获得我在ginput()
中点击的最接近的索引,第一种方法与每次点击相距一段距离,并在下一步中找到最近的索引,第二种方法正在做同样的事情,但通过for
循环,第三个是第一个完全相同的副本,但减少了一步
ax = subplot(1,1,1)
plot(timestamps,datavalue)
hzoom = zoom(ax);
hzoom.Motion = 'horizontal';
[x, ~] = ginput(2);
%1)
tic;
tmp = abs(bsxfun(@minus,x,datenum(timestamps).'));
[~, idx1] = min(tmp,[],2);
toc;
%2)
tic;
for r = 1:length(x)
val = x(r);
tmp = abs(datenum(datenum(timestamps - val)));
[~, idx2] = min(tmp);
closest_indx(r) = idx2;
end
toc;
%3)
tic;
[~, idx3] = min(abs(bsxfun(@minus,x,datenum(timestamps).')),[],2);
toc;
现在我看结果
test1)
Elapsed time is 0.009182 seconds.
Elapsed time is 0.019211 seconds.
Elapsed time is 0.011261 seconds.
test2)
Elapsed time is 0.012625 seconds.
Elapsed time is 0.022681 seconds.
Elapsed time is 0.017999 seconds.
test3)
Elapsed time is 0.013053 seconds.
Elapsed time is 0.020170 seconds.
Elapsed time is 0.015248 seconds.
test4)
Elapsed time is 0.011613 seconds.
Elapsed time is 0.018644 seconds.
Elapsed time is 0.015952 seconds.
第一种方法花费的时间更少,即使它还有一步取得所有值并放入“tmp
”矩阵。有没有人对此有一个很好的解释?