0Pricing
C++ Academy · Lesson

Measuring Code Performance

Benchmark with chrono.

Why Benchmark?

Measuring how long code runs helps you find bottlenecks and verify optimizations. With <chrono> you get portable, type-safe timing.

  • Measure before optimizing.
  • Use a steady clock for reliable intervals.
#include <iostream>
#include <chrono>

int main() {
    using namespace std::chrono;
    auto start = steady_clock::now();
    auto end = steady_clock::now();
    std::cout << "Timed a block: " << ((end - start).count() >= 0) << '\n';
    return 0;
}

The Basic Pattern

The benchmarking pattern is always the same: capture now() before the work, run it, capture now() after, and subtract.

#include <iostream>
#include <chrono>

int main() {
    using namespace std::chrono;
    auto start = steady_clock::now();
    long sum = 0;
    for (int i = 0; i < 100000; ++i) sum += i;
    auto end = steady_clock::now();
    std::cout << "Sum: " << sum << ", elapsed >= 0: " << ((end - start).count() >= 0) << '\n';
    return 0;
}

All lessons in this course

  1. Durations and Clocks
  2. Time Points
  3. Measuring Code Performance
  4. Calendar and Time Zones
← Back to C++ Academy