Speeding up nested loops in python
<p>How can I speed up this code in python?</p>

<pre><code>while ( norm_corr &gt; corr_len ): 

    correlation = 0.0

    for i in xrange(6):
        for j in xrange(6):
            correlation += (p[i] * T_n[j][i]) * ((F[j] - Fbar) * (F[i] - Fbar))      

    Integral += correlation
    T_n =np.mat(T_n) * np.mat(TT)
    T_n = T_n.tolist()
    norm_corr = correlation / variance 
</code></pre>

<p>Here, TT is a fixed 6x6 matrix, p is a fixed 1x6 matrix, and F is fixed 1x6 matrix. T_n is the nth power of TT. </p>

<p>This while loop might be repeated for 10^4 times.</p>

<p>The way to do these things quickly is to use Numpy's built-in functions and operators to perform the operations. Numpy is implemented internally with optimized C code and if you set up your computation properly, it will run much faster.</p>

<p>But leveraging Numpy effectively can sometimes be tricky. It's called "vectorizing" your code - you have to figure out how to express it in a way that acts on whole arrays, rather than with explicit loops.</p>

<p>For example in your loop you have <code>p[i] * T_n[j][i]</code>, which IMHO can be done with a vector-by-matrix multiplication: if v is 1x6 and m is 6x6 then <code>v.dot(m)</code> is 1x6 that computes dot products of <code>v</code> with the columns of <code>m</code>. You can use transposes and reshapes to work in different dimensions, if necessary.</p>

python performance loops