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

Rounding functions for chrono durations and timepoints

Use case

Benchmark analysis passes.

Explanation

floor rounds down, ceil rounds up, round rounds to nearest.

Code

#include <chrono>
#include <iostream>
#include <thread>

int main() {
  using namespace std::chrono;

  auto start = high_resolution_clock::now();
  std::this_thread::sleep_for(1500ms);
  auto end = high_resolution_clock::now();

  auto elapsed = end - start;

  std::cout << "floor: " << floor<seconds>(elapsed).count() << "s.\n";
  std::cout << "ceil: " << ceil<seconds>(elapsed).count() << "s.\n";
  std::cout << "round: " << round<seconds>(elapsed).count() << "s.\n";
  std::cout << "exact: " << round<milliseconds>(elapsed).count() << "ms.\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/rounding-functions-for-chrono-durations-and-timepoints
floor: 1s.
ceil: 2s.
round: 2s.
exact: 1503ms.