matlabk-meanscpu-time

Matlab cputime with kmeans return 0


I am measuring the cputime taken by kmeans algorithm for each iteration using cputime feature. However, some iterations return cputime = 0. Here's my implementation:

   load fisheriris;
   [~,C] = kmeans(meas, 3, 'options',statset('MaxIter', 1),'Display', 'off');
   results=[];
   for i = 1:15
          t=cputime;
          [~,C] = kmeans(meas, 3, 'options',statset('MaxIter', 1),'Start',C, 'Display', 'off');
          elapsedCPUTime=cputime-t;
          results=[results;elapsedCPUTime];
   end 

This is the results I got for 15 iterations: 0, 0, 0.046875, 0, 0, 0, 0, 0, 0.03125, 0, 0, 0, 0, 0 ,0.03125. My first thought is that the computational time was too quick, hence 0 second. Is it true? If so, how can we achieve more precise cputime?

Thanks a lot.


Solution

  • From the documentation:

    To measure performance, it is recommended that you use the timeit or tic and toc functions. For more information, see Using tic and toc Versus the cputime Function.

    Following that link:

    Time a significant enough portion of code. Ideally, the code you are timing should take more than 1/10 second to run.

    Try running kmeans in a loop.

    load fisheriris;
    [~,C] = kmeans(meas, 3, 'options',statset('MaxIter', 1),'Display', 'off');
    results=[];
    for ii = 1:15
          t=cputime;
          for k = 1:100
              [~,Ctemp] = kmeans(meas, 3, 'options',statset('MaxIter', 1),'Start',C, 'Display', 'off');
          end
          elapsedCPUTime=(cputime-t)/100;
          C = Ctemp;
          results=[results;elapsedCPUTime];
    end
    

    Using i as the loop variable might yield unexpected results, which is why I changed it to ii.