C++ 将Python数组传递给c++;SWIG函数
我已经用python编写了很多代码,效果非常好。但是现在我正在扩大我正在分析的问题的规模,python的速度非常慢。python代码的慢部分是C++ 将Python数组传递给c++;SWIG函数,c++,python,multidimensional-array,swig,C++,Python,Multidimensional Array,Swig,我已经用python编写了很多代码,效果非常好。但是现在我正在扩大我正在分析的问题的规模,python的速度非常慢。python代码的慢部分是 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
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++程序/函数,它执行相同的计算,并且在相同的数据大小下在不到一秒钟的时间内执行。p>
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;
}
double sum=0;
双倍总数=0;
双tmp_num=0;
int-avesize=2;
对于(i=0+avesize;i您可以使用此处描述的数组:、SWIG库中的carray.i
或std_vector.i
。
我发现使用STD::从SWIG库中的向量更容易:代码> STDIVector .I/COD>将Python列表发送到C++ SWIG扩展。虽然在优化的情况下,它可能不是最佳的。
在您的情况下,您可以定义:
测试.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);
首先,我将介绍扩展Python的基础知识。请参见:
#ifndef TEST_H__
#define TEST_H__
#include <stdio.h>
#include <vector>
void print_array(std::vector< std::vector < int > > myarray);
#endif /* TEST_H__ */
#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]);
}
>>> 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]