[Numpy-discussion] python numpy code many times slower than c++

Christopher Barker Chris.Barker@noaa....
Wed Jan 21 11:44:29 CST 2009


Neal Becker wrote:
> I tried a little experiment, implementing some code in numpy 

It sounds like you've found your core issue, but a couple comments:

 > from numpy import *

I'm convinced that "import *" is a bad idea. I think the "standard" 
syntax is now "import numpy as np"

 > from math import pi

numpy already has pi -- I find I never need math, if I'm using numpy.



def db_to_volt (db):
     return 10**(0.05*db)

...

class ampl (object):
...
         ampl_interp = linear_interp (vectorize (db_to_volt) (pin), 
db_to_volt (pout))


you shouldn't need to use vectorize here -- db_to_volt already takes 
array input. vectorize could kill performance, in fact.

ampl_interp = linear_interp(db_to_volt(pin), db_to_volt(pout))

should work fine.

also, if you want maximum performance, you can eliminate extraneous 
array creation in functions like that by:

1) using numexpr (see recent posts about it)
2) writing uglier code that explicitly passes in the output arrays:

def db_to_volt (db):
     a = 0.05*db
     np.power(10, a, a)

This will only help for large arrays, and help more for more complex 
functions.


A minor style nit:

I found it remarkably hard to read your code because of the spaces 
before the open parens for function calls:

func (arg1, arg2)

It's not just me: PEP 8 makes it very clear:

"""
Whitespace in Expressions and Statements

   Pet Peeves

     Avoid extraneous whitespace in the following situations:

     - Immediately before the open parenthesis that starts the argument
       list of a function call:

       Yes: spam(1)
       No:  spam (1)
"""

http://www.python.org/dev/peps/pep-0008/

I image you've used that style for years for lots of code, but I 
couldn't help myself!

-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov


More information about the Numpy-discussion mailing list