title: Optimize performance of loop
body: <p>I've been profiling a bottleneck in my code (a function shown below) that gets called several million times. I could use tips on increasing the performance. The <code>XXXs</code> numbers were taken from <a href="http://www.codersnotes.com/sleepy" rel="nofollow noreferrer">Sleepy</a>. </p>
  
  <p>Compiled with visual studio 2013, <code>/O2</code> and other typical release settings.</p>
  
  <p><code>indicies</code> is typically 0 to 20 values, and other parameters are the same size (<code>b.size() == indicies.size() == temps.size() == temps[k].size()</code>).</p>
  
  <pre><code>1:          double Object::gradient(const size_t j, 
  2:                                  const std::vector&lt;double&gt;&amp; b, 
  3:                                  const std::vector&lt;size_t&gt;&amp; indices, 
  4:                                  const std::vector&lt;std::vector&lt;double&gt;&gt;&amp; temps) const
  5:  23.27s  {
  6:              double sum = 0;
  7:  192.16s     for (size_t k : indices)
  8:  32.05s          if (k != j)
  9:  219.53s             sum += temps[k][j]*b[k];
  10:      
  11: 320.21s     return boost::math::isfinite(sum) ? sum : 0;
  13: 22.86s  }
  </code></pre>
  
  <p>Any ideas?</p>
  
  <p>Thanks for the tips guys. Here were the results I got from the suggestions:</p>
  
  <p><img src="https://i.stack.imgur.com/9Cq96.png" alt="enter image description here"></p>
  
  <p>I found it interesting that switching to <code>cbegin()</code> and <code>cend()</code> had such a large impact. I guess the compiler isn't being as smart as it could there. I'm happy with the bump, but still curious if there's more room here through unrolling or vectorization. </p>
  
  <p>For those interested, here my benchmark for <code>isfinite(x)</code>:</p>
  
  <pre><code>boost::isfinite(x):
  ------------------------
  SPEED: 761.164 per ms
  TIME:  0.001314 ms
     +/- 0.000023 ms
  
  std::isfinite(x):
  ------------------------
  SPEED: 266.835 per ms
  TIME:  0.003748 ms
     +/- 0.000065 ms
  </code></pre>