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

Sturla Molden sturla@molden...
Wed Jan 21 07:38:34 CST 2009


On 1/21/2009 1:27 PM, Neal Becker wrote:

> It might if I had used this for all of my c++ code, but I have a big library 
> of c++ wrapped code that doesn't use pyublas.  Pyublas takes numpy objects 
> from python and allows the use of c++ ublas on it (without conversion).

If you can get a pointer (as integer) to your C++ data, and the shape 
and dtype is known, you may use this (rather unsafe) 'fromaddress' hack:


http://www.mail-archive.com/numpy-discussion@scipy.org/msg04974.html


import numpy
def fromaddress(address, dtype, shape, strides=None):
     """
     Create a numpy array from an integer address, a dtype
     or dtype string, a shape tuple, and possibly strides.
     Make sure dtype is a dtype, not just "f" or whatever.
     """
     dtype = numpy.dtype(dtype)
     class Dummy(object): pass
     d = Dummy()
     d.__array_interface__ = dict(
         data = (address, False),
         typestr = dtype.str,
         descr = dtype.descr,
         shape = shape,
         strides = strides,
         version = 3,
     )
     return numpy.asarray(d)




Example:

 >>> a = numpy.zeros(10)
 >>> a
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
 >>> a.__array_interface__
{'descr': [('', '<f8')], 'strides': None, 'shape': (10,), 'version': 3, 
'typestr': '<f8', 'data': (20388752, False)}
 >>> b = fromaddress(20388752, numpy.float64, (10,))
 >>> b
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
 >>> b[0] = 1.0
 >>> a
array([ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])



Sturla Molden




More information about the Numpy-discussion mailing list