title: Matlab vs c++ speed comparison in this code
body: <p>I have written simple C++ code and tested it in C++, then I have adapted the same code for MATLAB by <code>mex file_name.cpp</code> and run the same code in MATLAB which is using the same compiler as C++. Here is the code: </p>
  
  <pre><code>int k;
  for(int j = 0; j &lt; 100;j++){
      for(int i = 0; i &lt; 10000000; i++){
          k++;
      }
      k/=10000000
  }
  </code></pre>
  
  <p>Here is MATLAB code:</p>
  
  <pre><code>double a;int j;int i;
  double* k;
  
  for(j = 0; j &lt; 100;j++){
      for(i = 0; i &lt; 10000000; i++){
          a = a+1;
      }
      a = a / 10000000;
  }
  
  plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
  k = mxGetPr(plhs[0]);
  *k = (double)a;
  </code></pre>
  
  <p>I have edited this code for MATLAB, i.e changing to suitable types, adding MEX-function etc and the results are approx 900ms in MATLAB as opposed to 3100 ms in C++.</p>
  
  <p>What I don't understand is both are running the same code and with the same compiler (in MATLAB I write <code>mex -setup</code> in command line and selected Visual Studio compiler as MEX compiler), however, MATLAB is around <strong>3.5 times faster</strong>. </p>
  
  <p>What is MATLAB doing to be that faster and what is C++ not doing? Could somebody please explain me why there is so huge difference? I have tried some other codes, all are 3-6 times faster in MATLAB. </p>
  
  <p><strong>My PC is 64-bit Windows 7, Visual Studio 2010 is used for C++, MATLAB is R2012b.</strong> </p>
  
  <p>Is it possible this is because of my Visual Studio version? If I change it to VS2012, would it be faster?</p>
  
  <p><a href="https://dl.dropboxusercontent.com/u/78608149/mex_v.txt" rel="nofollow">mex -v</a> output is here.</p>
  
  <p>Thanks,</p>