title: Find diagonals sums in numpy (faster)
body: <p>I have some <code>board</code> numpy arrays like that:</p>
  
  <pre><code>array([[0, 0, 0, 1, 0, 0, 0, 0],
         [1, 0, 0, 0, 0, 1, 0, 1],
         [0, 0, 0, 0, 0, 0, 0, 1],
         [0, 1, 0, 1, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 1],
         [0, 0, 0, 0, 1, 0, 0, 0],
         [0, 0, 1, 0, 0, 0, 1, 0],
         [1, 0, 0, 0, 0, 1, 0, 0]])
  </code></pre>
  
  <p>And I'm using the following code to find the sum of elements on each nth diagonal from -7 to 8 of the board (and the mirrored version of it).</p>
  
  <pre><code>n = 8
  rate = [b.diagonal(i).sum()
          for b in (board, board[::-1])
          for i in range(-n+1, n)]
  </code></pre>
  
  <p>After some profiling, this operation is taking about 2/3 of overall running time and it seems to be because of 2 factors:</p>
  
  <ul>
  <li>The <code>.diagonal</code> method builds a new array instead of a view (looks like numpy 1.7 will have a new <code>.diag</code> method to solve that)</li>
  <li>The iteration is done in python inside the list comprehension</li>
  </ul>
  
  <p>So, there are any methods to find these sums faster (possibly in the C layer of numpy)?</p>
  
  <hr>
  
  <p>After some more tests, I could reduce 7.5x the total time by caching this operation... Maybe I was looking for the wrong bottleneck?</p>
  
  <hr>
  
  <p>One more thing:</p>
  
  <p>Just found the <code>.trace</code> method that replaces the <code>diagonal(i).sum()</code> thing and... There wasn't much improvement in performance (about 2 to 4%).</p>
  
  <p>So the problem should be the comprehension. Any ideas?</p>