CodeBlanks Logo Icon CodeBlanks

Profiling

Learn performance measurement with profiling tools.

Profiling

Profiling measures where a program spends its time. Profile to act on data rather than guesses; often an unexpected function is the bottleneck.

In C++ time is measured with std::chrono::steady_clock: auto t0 = std::chrono::steady_clock::now(); for the start, auto t1 = std::chrono::steady_clock::now(); for the end. The elapsed time is the difference t1 - t0. On Linux use perf, with GCC use gprof, with Valgrind use callgrind.

Measuring with std::chrono

std::chrono::steady_clock is a monotonic clock; it never goes back. The now() call returns a time point; the difference between two points gives a duration.

To convert the duration to microseconds: auto us = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();. Here .count() extracts the number. This idiom is placed inside multiplier (benchmark) loops to measure a function's average time.

Practice Measure a time point

Add #include <chrono>. In main write auto t0 = std::chrono::steady_clock::now(); and auto t1 = std::chrono::steady_clock::now();. Then write std::cout << (t1 >= t0);.

Starter code

main.cpp
#include <iostream>
#include <chrono>

int main() {
    // Measure t0 and t1, compare and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <chrono>

int main() {
    auto t0 = std::chrono::steady_clock::now();
    auto t1 = std::chrono::steady_clock::now();
    std::cout << (t1 >= t0);
    return 0;
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does profiling measure?

main.cpp
auto t0 = std::chrono::steady_clock::now();
// ... work ...
auto t1 = std::chrono::steady_clock::now();
  • Where time is spent Correct answer
  • Compile time
  • Symbol count
  • Memory size

Explanation: Profiling shows the bottleneck with data.

2 Complete the now() call

Question
auto t0 = std::chrono::steady_clock::____();
Answer
auto t0 = std::chrono::steady_clock::now();

Explanation: now() returns the current time point.

3 Match each tool to its role

Term Meaning
perf Linux profiler
gprof GCC profiler
callgrind Valgrind profiler
std::chrono Duration measure

All lessons in Expert