Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::chrono

Use case

Bechmark analysis operations.

Explanation

std::chrono provides type-safe time handling. Get the current time with now(), subtract to get duration and cast to desired units with duration_cast. Use high_resolution_clock for benchmarking.

Code

#include <chrono>
#include <iostream>

void analyze() {
  volatile int sum = 0;
  for (int i = 0; i < 1000000; ++i) {
    sum += i;
  }
}

int main() {
  auto start = std::chrono::high_resolution_clock::now();
  analyze();
  auto end = std::chrono::high_resolution_clock::now();

  auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  auto us = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

  std::cout << "Elapsed: " << ms.count() << " ms (" << us.count() << " us).\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/std-chrono
Elapsed: 2 ms (2883 us).