Why does `minmax` take longer than consecutive` min` and `max`?
In general, in general, the question says it all, my intuition tells me that the call minmax
will take less time than the call min
, and then a max
.
Is there some kind of optimization that prevents Matlab from executing in the following code?
MINMAX:
function minmax_vals = minmaxtest()
buffSize = 1000000;
A = rand(128,buffSize);
windowSize = 100;
minmax_vals = zeros(128,buffSize/windowSize*2);
for i=1:(buffSize/windowSize)
minmax_vals(:,(2*i-1):(2*i)) = minmax(A(:,((i-1)*windowSize+1):(i*windowSize)));
end
end
separate min-max:
function minmax_vals = minmaxtest()
buffSize = 1000000;
A = rand(128,buffSize);
windowSize = 100;
minmax_vals = zeros(128,buffSize/windowSize*2);
for i=1:(buffSize/windowSize)
minmax_vals(:,(2*i-1)) = min(A(:,((i-1)*windowSize+1):(i*windowSize)),[],2);
minmax_vals(:,(2*i)) = max(A(:,((i-1)*windowSize+1):(i*windowSize)),[],2);
end
end
source to share
Summary
You can see the overhead because it is minmax
not completely confusing. Just enter
edit minmax
And you will see the function!
It looks like there is a data type conversion to nntype.data('format',x,'Data');
, which won't be the case for min
or max
and can be costly. This is for use with MATLAB neural network tools (nn) as it minmax
belongs to this toolbar.
In short, min
and max
are low-level, compiled functions (hence completely obfuscated) that don't require functionality from the nn toolbox.
Benchmark
Here's a slightly more isolated test, without your window and using timeit
a profiler instead. I've also included timings just for the data conversion used in minmax
! ... The test gets the min and max of each row in a large matrix, see the output graph here and the code below ...
It seems that there is a linear relationship between the number of lines and the time (as expected for a linear operator), but the rate is much greater for the combined ratio minmax
, while the individual operations of approximately 10x faster than equal. Also you can clearly see that data conversion takes longer than the min
then version max
!
function benchie()
K = zeros(10, 3);
for k = 1:10
n = 2^k;
A = rand(n, 200);
Arow = zeros(1,200);
m = zeros(n,2);
f1 = @()minmaxtest(A,m);
K(k,1) = timeit(f1);
f2 = @()minthenmaxtest(A,m);
K(k,2) = timeit(f2);
f3 = @()dataconversiontest(A, Arow);
K(k,3) = timeit(f3);
end
figure; hold on; plot(2.^(1:10), K(:,1)); plot(2.^(1:10), K(:,2)); plot(2.^(1:10), K(:,3));
end
function minmaxtest(A,m)
for ii = 1:size(A,1)
m(ii, 1:2) = minmax(A(ii,:));
end
end
function dataconversiontest(A, Arow)
for ii = 1:size(A,1)
Arow = nntype.data('format', A(ii,:), 'Data');;
end
end
function minthenmaxtest(A,m)
for ii = 1:size(A,1)
m(ii, 1) = min(A(ii,:));
m(ii, 2) = max(A(ii,:));
end
end
source to share