### Thread: Optimization in C/C++

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2004
Location
Bimingham,AL
Posts
68
Rep Power
11

#### Optimization in C/C++

Dear All,

I have the following function which i am thinking of writing in C/C++ bcos its taking ages to run that in python

Code:
def calculateCooccurence(self, matrix,intensityList):
coMatrix = zeros((len(intensityList),len(intensityList)))
for i in range(len(intensityList)):
ival = intensityList[i]
for j in range(len(intensityList)):
jval = intensityList[j]
for x in range(len(matrix)-1):
for y in range(len(matrix[0])-1):

if matrix[x][y] ==ival and matrix[x+1][y+1] =jval:
coMatrix[i][j] = coMatrix[i][j]+1

but inorder to do that i will have to pass a one dimesional and two dimensional list ( intensityList and matrix ) to C function and pass back a two dimensional array (coMatrix).

Can anyone help me with passing arrays back and forth between c and python
2. You should use the enumerate function for the first two for loops, this will make things easier to read. The function can probably be optimized but I will have to look at that later .

Personally I haven't played around with the CPython API but you can read more on this in the Python docs.

http://www.python.org/doc/2.3.4/ext/ext.html

You may also be interested in the cTypes library, which allows you to call C functions from Python.

http://starship.python.net/crew/theller/ctypes/

There are so many solutions for this kind of thing including Psyco, SWIG, Boost Python, Pyrex etc. I would suggest looking at some of these and seeing which will work best for your situation.

http://psyco.sourceforge.net/
http://www.swig.org/tutorial.html
http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/
http://boost.org/libs/python/doc/

Hope this helps,

Mark.

#### Comments on this post

• wx_uab agrees
3. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
London, England
Posts
1,585
Rep Power
1373
You should also check out Numerical Python and numarray.

They are both high-performance libraries for manipulating matrices.

Dave - The Developers' Coach