Coursework for the Master's course Computational Data Science: Advanced Programming
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

2.5 KiB

C++ versus Python performance

This exercise is intended to show explicitly the great difference that can exist between interpreted and compiled software. To illustrate the point, a few benchmarks have been lifted from the benchmarks game site. The benchmarks have been coded in such a way as to be algorithmically identical in the different programming languages.

Performance measurement

The task here is to carry out a performance measurement using the time program, running both the C++ and the Python version of each code. A general way to determine the time needed for a program to run is the following:

time ./myexe args

where args are any run-time arguments to the program. (The ./ prefix is not needed if you have the "current working directory" . in your PATH; however, doing so is generally considered bad practice, as it is insecure.) Note that all three programs take arguments that will affect the computing time needed. In the Python case you would replace myexe with python3 (note that Python2 will likely fail to work).

How to run: C++

The general way to use (on Linux machines) the command-line g++ compiler illustrated below with a fictive source file called .

g++ -o myexe

Note that the C++ language standard is (still) evolving, and different programs adhere to different standards. The programs used here conform to the c++11 standard (which appears to be the default setting for the g++ version 7 compiler). Other standards could be specified using the -std=... option to g++. Many options to g++ exist; extensive information can be obtained by doing

man g++

Note also that instead of a command line tool, other (graphical) tools or Integrated Development Environments or IDEs may be used for your code development. As a general principle, the important thing is that whatever you do should work with a straight compilation using g++.


  • The spectral-norm code uses the OpenMP library to enable multi-threading, a topic that we will get to later. To compile this code, the -fopenmp compilation flag is needed.

  • The mandelbrot code produces a NetPBM graphics output file, but does so by writing it to its standard output. One way to redirect the output is to specify

      time ( ./myexe args > mandelbrot.pbm )

(The parentheses here are needed to create a sub-shell; without them, the outputs from the time command and from myexe would get mixed up.)