title: 3x3 Matrix determinant function - making it faster
body: <p>I'm writing a bigger program and getting the determinants of 3x3 matrices as fast as possible is pretty important for it to work well. I've read that I could use numPy to do it, but I thought that maybe writing my own code would be more educational as I'm in my 3rd semester of CompSci.</p>
  
  <p>So I wrote two functions and I'm using time.clock() (I'm on a win7 machine) to time how long it takes for each function to return a value. </p>
  
  <p>This is the first function:</p>
  
  <pre><code>def dete(a):
     x = (a[0][0] * a[1][1] * a[2][2]) + (a[1][0] * a[2][1] * a[3][2]) + (a[2][0] * a[3][1] * a[4][2])
     y = (a[0][2] * a[1][1] * a[2][0]) + (a[1][2] * a[2][1] * a[3][0]) + (a[2][2] * a[3][1] * a[4][0])
     return x - y
  </code></pre>
  
  <p>And this is the second function:</p>
  
  <pre><code>def det(a):
      a.append(a[0]); a.append(a[1]);
      x = 0
      for i in range(0, len(a)-2):
          y=1;        
          for j in range(0, len(a)-2):    
              y *= a[i+j][j]      
          x += y
  
      p = 0
      for i in range(0, len(a)-2):
          y=1;
          z = 0;
          for j in range(2, -1, -1):  
              y *= a[i+z][j]  
              z+=1        
          z += 1
          p += y  
      return x - p
  </code></pre>
  
  <p>They both give the correct answers, however the first one seems to be slightly faster, which makes me think that since for-loops are more elegant to use and usually faster, I'm doing something wrong - I made the loops too slow and fat. I tried trimming it down, but it seems that the *= and += operations are taking too much time, there's too many of them.
  I haven't checked how fast numPy takes care of this problem yet, but I wanna get better at writing efficient code.
  Any ideas on how to make those loops faster?</p>