Python speed vs csharp

Richie Hindle richie at entrian.com
Thu Jul 31 08:39:47 EDT 2003


[Mike]
> is there anything that can be done to get Python's speed close
> to the speed of C#?

Using Pyrex takes a million loops from 7.1 seconds to 1.3 seconds for me:

------------------------------- mike.pyx -------------------------------

cdef extern from "math.h":
    double exp(double x)

def erfc(x):
    cdef double f_x, p, a1, a2, a3, a4, a5, t
    
    f_x = x
    
    p  =  0.3275911
    a1 =  0.254829592
    a2 = -0.284496736
    a3 =  1.421413741
    a4 = -1.453152027
    a5 =  1.061405429
    
    t = 1.0 / (1.0 + p*f_x)
    return ( (a1 + (a2 + (a3 + (a4 + a5*t)*t)*t)*t)*t ) * exp(-(f_x**2))
    

------------------------------- setup.py -------------------------------

# Run with "python setup.py build"
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
  name = "Mike",
  ext_modules=[ 
    Extension("mike", ["mike.pyx"])
    ],
  cmdclass = {'build_ext': build_ext}
)


------------------------------- test.py -------------------------------

# This takes about 1.3 seconds on my machine.
import time
from mike import erfc

if __name__ == '__main__':
    start = time.time()
    for i in xrange(1000000):
        erfc(123.456)
    print time.time() - start


-----------------------------------------------------------------------

Given that a million calls to "def x(): pass" take 0.9 seconds, the actual
calculation time is about 0.4 seconds, down from 6.2.  Not as fast as your
C# results, but a lot better than you had before.

Using Psyco dropped from 7.1 seconds to 5.4 - not great, but not bad for
two lines of additional code:

    import psyco
    psyco.bind(erfc)

Psyco currently only works on Intel-x86 compatible processors.

Hope that helps,

-- 
Richie Hindle
richie at entrian.com






More information about the Python-list mailing list