2011-03-09 19 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