title: c++ loop unroll performance
body: <p>I was reading 'C++ Template complete guide' book, part about meta programming. There is an example of loop unroll (17.7). I've implemented the program for dot product calculations:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;sys/time.h&gt;
  
  using namespace std;
  
  template&lt;int DIM, typename T&gt;
  struct Functor
  {
      static T dot_product(T *a, T *b)
      {
          return *a * *b + Functor&lt;DIM - 1, T&gt;::dot_product(a + 1, b + 1);
      }
  };
  
  template&lt;typename T&gt;
  struct Functor&lt;1, T&gt;
  {
      static T dot_product(T *a, T *b)
      {
          return *a * *b;
      }
  };
  
  
  template&lt;int DIM, typename T&gt;
  T dot_product(T *a, T *b)
  {
      return Functor&lt;DIM, T&gt;::dot_product(a, b);
  }
  
  double dot_product(int DIM, double *a, double *b)
  {
      double res = 0;
      for (int i = 0; i &lt; DIM; ++i)
      {
          res += a[i] * b[i];
      }
      return res;
  }
  
  
  int main(int argc, const char * argv[])
  {
      static const int DIM = 100;
  
      double a[DIM];
      double b[DIM];
  
      for (int i = 0; i &lt; DIM; ++i)
      {
          a[i] = i;
          b[i] = i;
      }
  
  
      {
          timeval startTime;
          gettimeofday(&amp;startTime, 0);
  
          for (int i = 0; i &lt; 100000; ++i)
          {
              double res = dot_product&lt;DIM&gt;(a, b); 
              //double res = dot_product(DIM, a, b);
          }
  
          timeval endTime;
          gettimeofday(&amp;endTime, 0);
  
          double tS = startTime.tv_sec * 1000000 + startTime.tv_usec;
          double tE = endTime.tv_sec   * 1000000 + endTime.tv_usec;
  
          cout &lt;&lt; "template time: " &lt;&lt; tE - tS &lt;&lt; endl;
      }
  
      {
          timeval startTime;
          gettimeofday(&amp;startTime, 0);
  
          for (int i = 0; i &lt; 100000; ++i)
          {
              double res = dot_product(DIM, a, b);
          }
  
          timeval endTime;
          gettimeofday(&amp;endTime, 0);
  
          double tS = startTime.tv_sec * 1000000 + startTime.tv_usec;
          double tE = endTime.tv_sec   * 1000000 + endTime.tv_usec;
  
          cout &lt;&lt; "loop time: " &lt;&lt; tE - tS &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>I'm using xcode and I turned all code optimisations off. I expected that template version have to be faster then simple loop according to the book. But the results are (t - Template, l = Loop):</p>
  
  <p>DIM 5: t = ~5000, l = ~3500</p>
  
  <p>DIM 50: t = ~55000, l = 16000</p>
  
  <p>DIM 100: t = 130000, l = 36000</p>
  
  <p>Also i've tried to make template functions inline with no performance difference.</p>
  
  <p>Why simple loop is so much faster? </p>