SVN / public / code / vorlesung-09 / Timer.h

Revision 8201
Date
Committerhb1003
Download
// Copyright 2026, University of Freiburg
// Chair of Algorithms and Data Structures
// Author: Hannah Bast <bast@cs.uni-freiburg.de>

#include <chrono>
#include <iomanip>
#include <iostream>

// A simple timer class for demonstration purposes in Vorlesung 9.
//
// NOTE: This starts the timer as soon as the object is created. A more refined
// class would have methods `start()`, `stop()`, and `reset()`.
class Timer {
public:
  // Create a timer and start it right away.
  Timer() { time_ = std::chrono::steady_clock::now(); }

  // How many millseconds have passed since the timer was created.
  size_t msecsSinceStart() const {
    auto now = std::chrono::steady_clock::now();
    auto duration =
        std::chrono::duration_cast<std::chrono::milliseconds>(now - time_);
    return duration.count();
  }

private:
  // The time point when the timer was created.
  std::chrono::steady_clock::time_point time_;
};

// Overload the `operator<<`.
std::ostream &operator<<(std::ostream &os, const Timer &timer) {
  os << std::setw(4) << timer.msecsSinceStart() << " ms";
  return os;
}