2011-03-09 18 views
6

我已經在python中編寫了很多代碼,它的效果很好。但是現在我正在擴大我正在分析的問題的規模,而python的速度非常慢。 Python代碼的慢速部分是傳遞Python數組到C++函數與SWIG

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]) 

當H和W等於1024時,函數需要大約5分鐘才能執行。我寫了一個簡單的C++程序/函數,執行相同的計算,並在不到一秒鐘內以相同的數據大小執行操作。

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; 

     } 

我有一些其他的方法來執行二維數組。列出的是一個簡單的例子。

我想要做的是傳遞一個Python二維數組到我的C++函數並返回一個二維數組回到python。

我讀過一些關於swig的內容,並且討論了一些常見的問題,看起來這是一個可能的解決方案。但我似乎無法弄清楚我實際需要做什麼。

我可以得到任何幫助嗎?謝謝

+0

我開始首先是Python。請參閱:http://docs.python.org/extending/ – Santa 2011-03-09 19:33:02

回答

10

您可以使用如下所示的陣列:Doc - 5.4.5 Arrayscarray.istd_vector.i來自SWIG庫。 我發現使用SWIG庫std_vector.i的std :: vector將python列表發送到C++ SWIG擴展更容易。儘管在你的情況下優化很重要,但它可能不是最優的。

在你的情況,你可以定義:

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]); 
} 

如果您運行下面的Python代碼(我用的蟒蛇2.6.5),你可以看到,C++函數可以訪問Python列表:通過覆蓋擴展的基礎

>>> 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

謝謝,這正是我編碼,它運作良好。 – JMD 2011-04-04 17:47:33