function timeGrowingArrays(count, chunksize, xdim, nrep)
% timeGrowingArrays(count, chunksize, xdim, nrep)
%
% Time growth of arrays.
%
% INPUT:  count --> iteration count           [default: 100000]
%     chunksize --> growth chunk size         [default:   1000]
%          xdim --> dimension of obj to store [default:     10]
%          nrep --> repetitions for timing    [default:      1]
%
% OUTPUT:  none (direct text output)
%

% defaults
if (nargin < 1),     count = 100000; end
if (nargin < 2), chunksize =   1000; end
if (nargin < 3),      xdim =     10; end
if (nargin < 4),      nrep =      1; end

% display info
fprintf('Loop count: %6d\n', count);
fprintf(' chunksize: %6d\n', chunksize);
fprintf('      xdim: %6d\n', xdim);
fprintf('      nrep: %6d\n', nrep)

% Only the for loop itself
fprintf('Running plain for loop... ');
ticID = tic();
for n = 1:nrep
   for k=1:count
      % doing nothing
   end
end
times.forloop = toc(ticID);
fprintf('--- %15s took %12.8f s', 'for loop', times.forloop);
fprintf('\n')

% storage thing
thing = 1:xdim;


% Chunk growth
fprintf('Running chunked growth... ');
ticID = tic();
for n = 1:nrep
   X = zeros(chunksize, xdim);  % preallocate chunk
   Xfill = 1;                   % fill pointer
   Xsize = chunksize;           % size of array
   for k=1:count
      if (Xfill > Xsize)
         Xsize = Xsize + chunksize;
         X(Xsize, end) = 0;     % grow array by chunksize
      end
      Xfill = Xfill + 1;        % fill pointer not necessary for this
      X(Xfill,:) = thing;       % example, but in many practical cases
   end
end
times.chunkGrowth = toc(ticID);
fprintf('--- %15s took %12.8f s', 'chunk growth', times.chunkGrowth);
fprintf('  CheckSum =  %d\n', sum(X, 'all'));


% Growing array
fprintf('Running growing arrays... ');
ticID = tic();
for n = 1:nrep
   X = [];
   for k=1:count
      X(k,:) = thing;
   end
end
times.growingArray = toc(ticID);
fprintf('--- %15s took %12.8f s', 'growing array', times.growingArray);
fprintf('  CheckSum =  %d\n', sum(X, 'all'));  % check result



% display results
fprintf('\nResults:\n');
fields = fieldnames(times);
for k = 1:length(fields)
   f = fields{k};
   fprintf('Time of %12s: %12.8f s/rep\n', f, times.(f) / nrep);
end


end



