Exercise session 09


Optimization, debugging, profiling, testing.


Advanced Programming - SISSA, UniTS, 2024-2025

Pasquale Claudio Africa
25 Nov 2024

Optimization and profiling

Source

Memory layout

Data structure alignment

class MyClass
{
  char a;      // 1 byte.
  short int b; // 2 bytes.
  int c;       // 4 bytes.
  char d;      // 1 byte.
};

How data is not stored

How data is actually stored

Access patterns and loop tiling (for a row-major matrix)

Examples

The folder examples/optimization contains three examples:

  1. data_alignment compares the memory occupation of two objects containing the same data members but with different data alignment/padding.
  2. loop_unrolling implements a function that multiplies all elements in a std::vector by looping over all its elements and returns the result. The executable compares the performance with those obtained exploiting loop unrolling.
  3. static implements a function that allocates a std::vector and, taking an index as input, returns the corresponding value. The executable compares the performance with those obtained by declaring the vector static.

Exercise 1: Optimization

The hints/ex1/ directory contains the implementation of a class for dense matrices organized as column-major.

  • Implement Matrix::transpose(), a method to compute .
  • Implement operator*, a function to compute matrix-matrix multiplication.
  • Optimize the matrix-matrix multiplication by transposing the first factor before the computation. Compare the execution speed with the previous implementation.
  • Use valgrind --tool=callgrind to generate a profiler report.
  • Generate a coverage report using lcov and genhtml.

Debugging

Examples

The content of examples/debug was inspired by this repository and shows basic techniques for debugging as well as an introduction to gdb.

Further readings

Exercise 2: Debugging

The hints/ex2/ directory contains an implementation of a double-linked list class. The class stores a pointer to the head, and each node (except for the head and the tail, obviously) contains a pointer to the previous and to the next node.

The implementation contains a lot of errors, namely:

  1. Compilation and syntax errors.
  2. Runtime errors, including a segmentation fault and a problem in printing the list.
  3. Memory leaks.
  4. Two possible segmentation faults, not captured by the main.

With the help of gdb and valgrind, solve all these issues and make the code working!

Testing

Exercise 3: Testing

The hints/ex3/ contains a static function to compute the mean of a std::vector.

Following the given directory structure and using Google Test, fill in the missing parts in tests/mean.cpp to check that the function behaves as expected in all the listed cases.

To run the testsuite type

make test

or

ctest

from the CMake build folder.