About the C++ module

Contents

About the C++ module#

A simple molecular dynamics loop did everything from Python, yet the work inside sim.run() is done by an engine written in C++.

Detour: why the engine is not Python

I built this project to learn C++, because plain Python was getting abysmally slow for the applications I was building. A molecular simulation shows why in one loop: every step of a run visits every pair of atoms, and this is how slow that gets in Python. The same pass over all pairs of 512 atoms, written once in plain Python and once in C++ (examples/why_cpp/pairs.py and pairs.cpp), gives the same energy and very different times:

$ python3 pairs.py
python: U = -2695.565361   57.2 ms per pass
$ g++ -O3 -std=c++17 pairs.cpp -o pairs && ./pairs
c++:    U = -2695.565361   1.81 ms per pass

The C++ pass is about 30 times faster (Python 3.13, and g++ 8.5 with -O3, which asks the compiler to optimise for speed, both on one core of an AMD EPYC 7763). A run of 4000 steps makes 4000 passes: about four minutes of this loop in Python, about seven seconds in C++. A C++ compiler turns the loop into the processor’s own instructions once, before the program runs. Python turns it into bytecode, its own instruction list, and a program called the interpreter then carries out those instructions one at a time, on every one of the 130,816 pair visits of every pass.

The linked terms each get a proper introduction later: the compiler and the processor’s instructions in A first program, cores in the parallel module. Here only the two times matter.

So the engine computes in C++, and Python only sets up the run and starts it. This module covers enough of the language to read the engine, one chapter at a time, with one running example: a small program that computes the Lennard-Jones energy of two atoms. Each chapter adds a few lines to it. Chapter 5 arrives at the shape of the real engine’s energy-function plug from A simple molecular dynamics loop, and chapter 6 splits the program into files, the way the engine is organised.

Every example is a complete file you can compile and run. The outputs shown on the pages come from running those files. Each chapter ends with a few questions; click a question to see its answer.

Chapters:

  1. A first program

  2. Functions

  3. Many values: vectors and loops

  4. Classes

  5. The plug: inheritance and virtual functions

  6. Several files: headers, source files and linking

Next#

Start with A first program. You need a terminal and a C++ compiler; the chapter shows the commands that compile and run the program.