Conclusion after running some test codes: 1) The reason that in your codes, mean2
appear to be slower when iteration number is larger than 1000 is because of the penalty for organizing codes into function. MATLAB needs to create a scope for function and terminates it when function call ends This can been seen from the test condition below in which I implement the mean2 directly in the codes. 2) Per @rayryeng's comment, unrolling first speeds up computation when array is large(at least within my test conditions). 3) The 'double'
argument in sum(Ig(:),'double')
takes up some time and is actually unnecessary because sum
returns double
data type even without that argument.
The codes I used for test are as follows:
Img = rgb2gray(imread('test2.tif')); % this is an rgb image larger than 1000x1000
Ig = Img(1:250,1:250);
n = 100000;
tic
for ii=1:n
M1 = sum(sum(Ig))/numel(Ig);
end
toc
disp(' for sum(sum(Ig))/numel(Ig) 250x250')
tic;
for ii=1:n
M2 = mean2(Ig);
end
toc
disp(' for mean2(Ig) 250x250')
tic;
for ii=1:n
M3 = sum(Ig(:),'double')/numel(Ig);
end
toc
disp(' for sum(Ig(:),''double'')/numel(Ig) 250x250')
tic;
for ii=1:n
M4 = sum(Ig(:))/numel(Ig);
end
toc
disp(' for sum(Ig(:))/numel(Ig) 250x250')
clear M1 M2 M3 M4
Ig = Img(1:500,1:500);
tic
for ii=1:n
M1 = sum(sum(Ig))/numel(Ig);
end
toc
disp(' for sum(sum(Ig))/numel(Ig) 500x500')
tic
for ii=1:n
M2 = mean2(Ig);
end
toc
disp(' for mean2(Ig) 500x500')
tic
for ii=1:n
M3 = sum(Ig(:),'double')/numel(Ig);
end
toc
disp(' for sum(Ig(:),''double'')/numel(Ig) 500x500')
tic
for ii=1:n
M4 = sum(Ig(:))/numel(Ig);
end
toc
disp(' for sum(Ig(:))/numel(Ig) 500x500')
Ig = Img(1:1000,1:1000);
tic
for ii=1:n
M1 = sum(sum(Ig))/numel(Ig);
end
toc
disp(' for sum(sum(Ig))/numel(Ig) 1000x1000')
tic
for ii=1:n
M2 = mean2(Ig);
end
toc
disp(' for mean2(Ig) 1000x1000')
tic
for ii=1:n
M3 = sum(Ig(:),'double')/numel(Ig);
end
toc
disp(' for sum(Ig(:),''double'')/numel(Ig) 1000x1000')
tic
for ii=1:n
M4 = sum(Ig(:))/numel(Ig);
end
toc
disp(' for sum(Ig(:))/numel(Ig) 1000x1000')
and the results are :
Elapsed time is 2.115313 seconds.
for sum(sum(Ig))/numel(Ig) 250x250
Elapsed time is 5.753932 seconds.
for mean2(Ig) 250x250
Elapsed time is 5.626373 seconds.
for sum(Ig(:),'double')/numel(Ig) 250x250
Elapsed time is 5.425690 seconds.
for sum(Ig(:))/numel(Ig) 250x250
Elapsed time is 6.349700 seconds.
for sum(sum(Ig))/numel(Ig) 500x500
Elapsed time is 6.810287 seconds.
for mean2(Ig) 500x500
Elapsed time is 6.840604 seconds.
for sum(Ig(:),'double')/numel(Ig) 500x500
Elapsed time is 6.455498 seconds.
for sum(Ig(:))/numel(Ig) 500x500
Elapsed time is 23.772897 seconds.
for sum(sum(Ig))/numel(Ig) 1000x1000
Elapsed time is 22.071418 seconds.
for mean2(Ig) 1000x1000
Elapsed time is 21.862069 seconds.
for sum(Ig(:),'double')/numel(Ig) 1000x1000
Elapsed time is 21.498514 seconds.
for sum(Ig(:))/numel(Ig) 1000x1000