Compact Python library for math statistics

Paul Prescod paul at prescod.net
Fri Apr 9 20:03:28 EDT 2004


beliavsky at aol.com wrote:

>...
> 
> Overall, the Python code below is about 100 times slower than the
> Fortran equivalent. This is a typical ratio I have found for code
> involving loops.
> 
> from math import sqrt
> n = 10000000 + 1
> sum_sqrt = 0.0
> for i in range(1,n):
>     sum_sqrt = sum_sqrt + (float(i))**0.5
> print sum_sqrt

If you rewrite it as Pyrex:

def func5(int n):
     cdef float sum_sqrt
     cdef long int i

     sum_sqrt = 0.0
     for i from 0 <= i < n:
         sum_sqrt = sum_sqrt + i**0.5
     return sum_sqrt

This generates:

   for (i = 0; i < n; ++i) {

     sum_sqrt = (sum_sqrt + pow(i, 0.5));
     __pyx_L2:;
    }

Except for the useless label, this is idiomatic C code and I doubt that 
Fortran is going to be much of any faster given most compilers.

Even so, on my computer, this code is nowhere near 100 times faster than 
the pure Python version. I think you are timing the allocation of a very 
large memory buffer with range(). Consider this alternative:

def func1(n):
         sum_sqrt = 0.0
         for i in xrange(1,n):
              sum_sqrt = sum_sqrt + sqrt(i)
         return sum_sqrt

or

def func2(n):
         return sum(itertools.imap(sqrt, xrange(1, n)))

  Paul Prescod






More information about the Python-list mailing list