# [Tutor] how to speed up this code?

Andrew P grouch at gmail.com
Thu Oct 13 10:02:35 CEST 2005

```It's way past my bedtime, but any use of numpy/numarray that involves two
nested for loops to step over each element is the wrong solution :) You need
to figure out how to get rid of that inner for. That is what is slowing you
down.

Compare these two ways to multiply a 1000 element array by 100. The first
one steps over the elements one at a time, multiplying each one in turn. The
second multiplies the entire array at once. Which boils down to looping over
2000 rows, instead of 4,000,000 elements :)

If I was more awake, I'd try to figure out how you can do that. But this
should give you an idea of what arrays are useful for, and how to approach
the problem.

>>> def time_loop(num):
... a = arange(1000)
... b = zeros(1000)
... t = time.clock()
... for i in range(num):
... for i in range(len(a)):
... b[i] = a[i] * 100.0
... print time.clock() - t
...
>>> time_loop(100000)
59.7517100637

>>> def time_numeric(num):
... a = arange(1000)
... b = zeros(1000)
... t = time.clock()
... for i in range(num):
... b = a*100
... print time.clock() - t
...
>>> time_numeric(100000)
1.44588097091

On 10/13/05, Pujo Aji <ajikoe at gmail.com> wrote:
>
> I have code like this:
> def f(x,y):
> return math.sin(x*y) + 8 * x
>
> def main():
> n = 2000
> a = zeros((n,n), Float)
> xcoor = arange(0,1,1/float(n))
> ycoor = arange(0,1,1/float(n))
>
> for i in range(n):
> for j in range(n):
> a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x
>
> print a[1000,1000]
> pass
>
> if __name__ == '__main__':
> main()
>
> I try to make this run faster even using psyco, but I found this still
> slow, I tried using java and found it around 13x faster...
>
> public class s1 {
>
> /**
> * @param args
> */
> public static int n = 2000;
> public static double[][] a = new double[n][n];
> public static double [] xcoor = new double[n];
> public static double [] ycoor = new double[n];
>
> public static void main(String[] args) {
> // TODO Auto-generated method stub
> for (int i=0; i<n; i++){
> xcoor[i] = i/(float)(n);
> ycoor[i] = i/(float)n;
> }
>
> for (int i=0; i<n; i++){
> for (int j=0; j<n; j++){
> a[i][j] = f(xcoor[i], ycoor[j]);
> }
> }
>
> System.out.println(a[1000][1000]);
>
> }
> public static double f(double x, double y){
> return Math.sin(x*y) + 8*x;
> }
>
> }
>
> Can anybody help?
>
> pujo
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20051013/778485ab/attachment-0001.htm
```