September 03, 2019

Creating a C++ library with Boost Python

A short tutorial in the internet https://www.mantidproject.org/Boost_Python_Introduction have shown, how to combine C++ with Python. The C++ compiler is used to create a C++ library, and the Boost Python add on is used, to include this library in external Python programs.

Unfortunately, the recommended command line for starting the g++ compiler doesn't work in Fedora Linux. The correct parameter is:

g++ -Wall -Wextra -fPIC -shared -I/usr/include/python3.7m/ -lboost_python37 mantid.cpp -o mantid.so


The reason is, that the name of boost_python library is called slightly different in the current Fedora OS. All the library can be found in the directory /usr/lib64 The other options for the g++ compiler like the “-shared” switch are needed to create a “.so” library but not a standalone program.

Now we can go over to the funny part and test the newly created C++ library from within the python interpreter. We are creating a simple hello world app and measure the time.

import mantid
for i in range(1000000):
  print(i)
  mantid.sayHello()

"""
time python3 hello.py
real 0m13.070s
user 0m8.649s
sys 0m4.289s
"""

The program was able to execute 76923 requests per seconds. Only to get a comparison, a Python program which gets access to a C++ program over a RESTful interface will with a speed of 379 requests per seconds, https://trollheaven.blogspot.com/2019/08/testing-performance-of-restful-api-with.html That means, the boost Python framework is much faster then the RESTful interface.