2011-03-09 15 views
6

he escrito un buen trozo de código en Python y funciona muy bien. Pero ahora estoy escalando el tamaño de los problemas que estoy analizando y Python es tremendamente lento. La parte lenta del código Python esgama de Python a C++ con la función TRAGO

for i in range(0,H,1): 
     x1 = i - length 
     x2 = i + length 
     for j in range(0,W,1): 
      #print i, ',', j # check the limits 
      y1 = j - length 
      y2 = j + length 
      IntRed[i,j] = np.mean(RawRed[x1:x2,y1:y2]) 

Con H y W igual a 1024 la función de toma alrededor de 5 minutos a excute. He escrito un programa/función simple de C++ que realiza el mismo cálculo y se ejecuta en menos de un segundo con el mismo tamaño de datos.

double summ = 0; 
    double total_num = 0; 
    double tmp_num = 0 ; 
    int avesize = 2; 
    for(i = 0+avesize; i <X-avesize ;i++) 
    for(j = 0+avesize;j<Y-avesize;j++) 
     { 
     // loop through sub region of the matrix 
     // if the value is not zero add it to the sum 
     // and increment the counter. 
     for(int ii = -2; ii < 2; ii ++) 
      { 
      int iii = i + ii; 
      for(int jj = -2; jj < 2 ; jj ++) 
       { 
       int jjj = j + jj; 
       tmp_num = gsl_matrix_get(m,iii,jjj); 
       if(tmp_num != 0) 
        { 
        summ = summ + tmp_num; 
        total_num++; 
        } 


       } 
      } 
     gsl_matrix_set(Matrix_mean,i,j,summ/total_num); 
     summ = 0; 
     total_num = 0; 

     } 

Tengo otros métodos para realizar en la matriz 2D. El que está en la lista es un ejemplo simple.

Lo que quiero hacer es pasar una matriz 2D python a mi función C++ y devolver una matriz 2D a python.

He leído un poco sobre swig y he consultado preguntas anteriores, y parece que es una posible solución. Pero no puedo entender lo que realmente necesito hacer.

¿Puedo obtener alguna ayuda? Gracias

+0

me gustaría empezar cubriendo los conceptos básicos de la ampliación Python primero. Ver: http://docs.python.org/extending/ – Santa

Respuesta

10

Puede utilizar matrices como se describe aquí: Doc - 5.4.5 Arrays, carray.i o std_vector.i de la biblioteca SWIG. Me resulta más fácil trabajar con std :: vector de la biblioteca SWIG std_vector.i para enviar una lista de Python a una extensión C++ SWIG. Aunque en su caso la optimización importa, puede que no sea la óptima.

En su caso se puede definir:

test.i

%module test 
%{ 
#include "test.h" 
%} 

%include "std_vector.i" 

namespace std { 
%template(Line) vector <int>; 
    %template(Array) vector < vector < int> >; 
} 

void print_array(std::vector< std::vector <int> > myarray); 

test.h

#ifndef TEST_H__ 
#define TEST_H__ 

#include <stdio.h> 
#include <vector> 

void print_array(std::vector< std::vector <int> > myarray); 

#endif /* TEST_H__ */ 

test.cpp

#include "test.h" 

void print_array(std::vector< std::vector <int> > myarray) 
{ 
    for (int i=0; i<2; i++) 
     for (int j=0; j<2; j++) 
      printf("[%d][%d] = [%d]\n", i, j, myarray[i][j]); 
} 

Si ejecuta el siguiente código Python (utilicé Python 2.6.5), se puede ver que la función de C++ se puede acceder a la lista de pitón:

>>> import test 
>>> a = test.Array() 
>>> a = [[0, 1], [2, 3]] 
>>> test.print_array(a) 
[0][0] = [0] 
[0][1] = [1] 
[1][0] = [2] 
[1][1] = [3] 
+0

Gracias es exactamente lo que codifiqué y funcionó muy bien. – JMD

Cuestiones relacionadas