Boost is a C++ library that can interface with Python. Download it from http://www.boost.org/users/download/. The latest Boost version at the time of writing was 1.56.0. The easiest but also slowest installation method involves the following commands:
$ ./bootstrap.sh --prefix=/path/to/boost $ ./b2 install
The prefix
argument specifies the installation directory. In this example, we will assume that Boost was installed under the user's home
directory in a directory called Boost (such as ~/Boost
). In this directory, a lib
and include
directory will be created. For Unix and Linux, it is useful to run the following command:
export LD_LIBRARY_PATH=$HOME/Boost/lib:${LD_LIBRARY_PATH}
On Mac OS X, set the following environment variable:
export DYLD_LIBRARY_PATH=$HOME/Boost/lib
Redefine a rain summation function as given in the boost_rain.cpp
file in this book's code bundle:
#include <boost/python.hpp> double sum_rain(boost::python::list rain, int len) { double sum = 0.; for (int i = 0; i < len; i++){ int val = boost::python::extract<int>(rain[i]); if(val == -1) { sum += 0.025; } else { sum += 0.1 * val; } } return sum; } BOOST_PYTHON_MODULE(rain) { using namespace boost::python; def("sum_rain", sum_rain); }
The function accepts a Python list and the size of the list. Call the function from Python, as given in the rain_demo.py
file in this book's code bundle:
import numpy as np from rain import sum_rain rain = np.load('../rain.npy') print "Boost", sum_rain(rain.astype(int).tolist(), len(rain)) rain = .1 * rain rain[rain < 0] = .025 print "Numpy", rain.sum()
We will automate the development process with the Makefile
file in this book's code bundle:
CC = g++ PYLIBPATH = $(shell python-config --exec-prefix)/lib LIB = -L$(PYLIBPATH) $(shell python-config --libs) -L ${HOME}/Boost/lib -lboost_python OPTS = $(shell python-config --include) -O2 -I${HOME}/Boost/include default: rain.so @python ./rain_demo.py rain.so: rain.o $(CC) $(LIB) -Wl,-rpath,$(PYLIBPATH) -shared $< -o $@ rain.o: boost_rain.cpp Makefile $(CC) $(OPTS) -c $< -o $@ clean: rm -rf *.so *.o .PHONY: default clean
From the command line, run the following commands:
$ make clean;make
The results are identical as expected:
Boost 85291.55 Numpy 85291.55
3.21.244.217