[Numpy-discussion] Array interface and builtin array.array example
Filip Wasilewski
filip at ftv.pl
Tue Jul 11 18:36:11 CDT 2006
Hi,
the way of accessing data with __array_interface__, as shown by Travis
in [1], also works nicely when used with builtin array.array (if someone
here is still using it;).
Time to convert array.array to ndarray is O(N) but can be made O(1) just
by simple subclassing.
[1] http://aspn.activestate.com/ASPN/Mail/Message/numpy-discussion/3191164
cheers,
fw
-----------------------------------------------------------------------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import array as _array
import sys
if sys.byteorder == 'little':
_ENDIAN = '<'
else:
_ENDIAN = '>'
_TYPES_CONV ={
'c': '|u%%d', #character 1
'b': '|i%%d', #signed integer 1
'B': '|u%%d', #unsigned integer 1
'u': '%su%%d' % _ENDIAN, #Unicode character 2
'h': '%si%%d' % _ENDIAN, #signed integer 2
'H': '%su%%d' % _ENDIAN, #unsigned integer 2
'i': '%si%%d' % _ENDIAN, #signed integer 2 (4?)
'I': '%su%%d' % _ENDIAN, #unsigned integer 2 (4?)
'l': '%si%%d' % _ENDIAN, #signed integer 4
'L': '%su%%d' % _ENDIAN, #unsigned integer 4
'f': '%sf%%d' % _ENDIAN, #floating point 4
'd': '%sf%%d' % _ENDIAN, #floating point 8
}
class array(_array.array):
def __get_array_interface__(self):
new = {}
shape, typestr = (self.__len__(),), (_TYPES_CONV[self.typecode] % self.itemsize)
new['shape'] = shape
new['typestr'] = typestr
new['data'] = (self.buffer_info()[0], False) # writable
return new
__array_interface__ = property(__get_array_interface__, None, doc="array interface")
if __name__ == '__main__':
size = 1000000
typecode = 'f'
new = array(typecode, xrange(size))
old = _array.array(typecode, xrange(size))
import numpy
from time import clock as time
t1 = time()
nd = numpy.asarray(new)
t1 = time() - t1
#print nd
t2 = time()
nd = numpy.asarray(old)
t2 = time() - t2
#print nd
print "new:", t1
print "old:", t2
#EOF
More information about the Numpy-discussion
mailing list