Skip to content

Instantly share code, notes, and snippets.

@mattbierbaum
Created September 2, 2011 20:39
Show Gist options
  • Save mattbierbaum/1189856 to your computer and use it in GitHub Desktop.
Save mattbierbaum/1189856 to your computer and use it in GitHub Desktop.
Simple SWIG/numpy example
from distutils.core import setup, Extension
import numpy
import os
os.environ['CC'] = 'g++';
setup(name='matt_simple_test', version='1.0', ext_modules =[Extension('_simple',
['simple.cc', 'simple.i'], include_dirs = [numpy.get_include(),'.'])])
double dot(int n, double *a, int m, double *b){
double sum = 0.0;
for (int i=0; i<n; i++){
sum += a[i]*b[i];
}
return sum;
}
void create_list(int size, double *arr){
for (int i=0; i<size; i++)
arr[i] = i;
}
double dot(int n, double *a, int m, double *b);
void create_list(int size, double *arr);
double dot(int n, double *a, int m, double *b);
void create_list(int size, double *arr);
%module simple
%{
#define SWIG_FILE_WITH_INIT
#include "simple.h"
%}
%include "numpy.i"
%init %{
import_array();
%}
%apply (int DIM1, double* INPLACE_ARRAY1) {(int n0, double *a0)};
%apply (int DIM1, double* IN_ARRAY1) {(int n, double *a), (int m, double *b)};
%apply (int DIM1, double* ARGOUT_ARRAY1) {(int size, double *arr)};
%include "simple.h"
import simple
import numpy
from time import time
a = simple.create_list(1000000)
numpy_start = time()
print "Numpy says:", numpy.dot(a,a)
numpy_end = time()
swig_start = time()
print "SWIG says:", simple.dot(a,a)
swig_end = time()
print "Time of numpy:", (numpy_end-numpy_start)
print "Time of SWIG:", (swig_end-swig_start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment