Stopwatch class in C++ I needed to implement a stop watch like class that will be used to measure running time of different functions by others. The final running time needs to be printed in 9h 3min 2s 23s 32ms 87us 78ns format. If the larger units are zero then they must be omitted. Time duration in a particular time-unit like seconds or milliseconds can be obtained from functions similar to hours. I need better ideas to improve the implementation.

#ifndef _STOP_WATCH_HPP_
#define _STOP_WATCH_HPP_

#include &lt;chrono&gt;
#include &lt;utility&gt;
#include &lt;iostream&gt;

class stop_watch {
    std::chrono::high_resolution_clock::time_point last_time_point;
    std::chrono::duration&lt;double&gt; time_duration;
    bool is_running;
  public:
    stop_watch() : 
      last_time_point {std::chrono::high_resolution_clock::now()},
      time_duration {std::chrono::duration&lt;double&gt;::zero()},
      is_running {false}
      {}
    void start() {
      assert(!is_running); // stop watch is already running
      last_time_point = std::chrono::high_resolution_clock::now();
      time_duration = std::chrono::duration&lt;double&gt;::zero();
      is_running = true;
    }
    void stop() {
      assert(is_running); // stop watch is not running
      auto n = std::chrono::high_resolution_clock::now();
      time_duration = n - last_time_point;
      last_time_point = n;
      is_running = false;
    }
    double hours() {
      return std::chrono::duration_cast&lt;std::chrono::hours&gt;(
          time_duration).count();
    }
    friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, stop_watch sw) {
      std::chrono::hours h = std::chrono::duration_cast&lt;
          std::chrono::hours&gt;(sw.time_duration);
      if (h.count()) {out &lt;&lt; h.count() &lt;&lt; "h "; sw.time_duration -= h;}
      std::chrono::minutes m = std::chrono::duration_cast&lt;
          std::chrono::minutes&gt;(sw.time_duration);
      if (m.count()) {out &lt;&lt; m.count() &lt;&lt; "min "; sw.time_duration -= m;}
      std::chrono::seconds s = std::chrono::duration_cast&lt;
          std::chrono::seconds&gt;(sw.time_duration);
      if (s.count()) {out &lt;&lt; s.count() &lt;&lt; "s "; sw.time_duration -= s;}
      std::chrono::milliseconds ms = std::chrono::duration_cast&lt;
          std::chrono::milliseconds&gt;(sw.time_duration);
      if (ms.count()) {out &lt;&lt; ms.count() &lt;&lt; "ms "; sw.time_duration -= ms;}
      std::chrono::microseconds us = std::chrono::duration_cast&lt;
          std::chrono::microseconds&gt;(sw.time_duration);
      if (us.count()) {out &lt;&lt; us.count() &lt;&lt; "us "; sw.time_duration -= us;}
      std::chrono::nanoseconds ns = std::chrono::duration_cast&lt;
          std::chrono::nanoseconds&gt;(sw.time_duration);
      if (ns.count()) {out &lt;&lt; ns.count() &lt;&lt; "ns "; sw.time_duration -= ns;}
      return out;
    }
};

#endif


Sample usage

stop_watch sw;
sw.start();
// function(s) to measure time
sw.stop();
cout &lt;&lt; "It took " &lt;&lt; sw &lt;&lt; endl;


I need some guideline on how to do this more efficiently, as my code is already too messy :(. I also have the following questions:


Is there a way to generate the functions for hours, seconds, etc. dynamically?  
How can I improve the operator&lt;&lt; function? Is there a way to have a list of time units that I can iterate?
Misc.:


Modern compilers all support #pragma once. It's much cleaner than old-school include guards.
You need a #include &lt;cassert&gt;


Code Improvements - Class:


Use typedefs to reduce code duplication (and if you ever need to change the clock type, it's much simpler). These should be public.

using clock_t = std::chrono::high_resolution_clock;
using duration_t = clock_t::duration;

Store the duration type at the resolution of the clock, rather than using duration&lt;double&gt;.

clock_t::time_point last_time_point;
duration_t time_duration;

The hours function should be const, but I'd actually recommend replacing it with a function that returns the time in the most accurate units. The stopwatch class shouldn't worry about time conversions - only the user code knows the desired accuracy, and can duration_cast if necessary:

duration_t get_elapsed_time() const
{
    return time_duration;
}

Since the code asserts on the running state in start() and stop(), we probably need a function to check if the stopwatch is running:

bool get_is_running() const
{
    return is_running();
}



Code Improvements - Output:


Now that we have get_elapsed_time(), the ostream operator doesn't need to be a friend.
Use auto here too.
Doing the printing separately from extracting each unit of time makes things clearer.
The ostream operator should take the stopwatch by const&amp;, not by value. (I doubt it makes much difference performance-wise, but it makes the intent and semantics clearer -
surely we shouldn't need to copy the stopwatch object to print the time?). Outsourcing the printing to a separate function also makes things a bit neater (more lines of code, but less duplication). It could be a lambda function if you wanted.

namespace detail
{

    template&lt;class duration_t&gt;
    void print_duration_if_non_zero(std::ostream&amp; out, duration_t const&amp; duration, std::string const&amp; unitPostfix)
    {
        if (duration == duration_t::zero())
            return;

        out &lt;&lt; duration.count() &lt;&lt; unitPostfix;
    }

} // detail

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, stop_watch const&amp; sw) {

    auto t = sw.get_elapsed_time();

    auto h = std::chrono::duration_cast&lt;std::chrono::hours&gt;(t); t -= h;
    auto m = std::chrono::duration_cast&lt;std::chrono::minutes&gt;(t); t -= m;
    auto s = std::chrono::duration_cast&lt;std::chrono::seconds&gt;(t); t -= s;
    auto ms = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t); t -= ms;
    auto us = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(t); t -= us;
    auto ns = std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(t);

    detail::print_duration_if_non_zero(out, h, "h ");
    detail::print_duration_if_non_zero(out, m, "min ");
    detail::print_duration_if_non_zero(out, s, "s ");
    detail::print_duration_if_non_zero(out, ms, "ms ");
    detail::print_duration_if_non_zero(out, us, "us ");
    detail::print_duration_if_non_zero(out, ns, "ns ");

    return out;
}

It would be cleaner not to give stop_watch an ostream operator at all. If you create a print_time_to_stream(stream, time) that takes time as  std::chrono::nanoseconds (or whatever's the highest resolution you need in your app), then your print function can be used for any time, and not just for the stop_watch class!


Your Questions


get_elapsed_time() makes this unnecessary! User code should convert the duration when it needs to.
Since std::chrono::hours etc. are types, they can't just be added to a vector. I suppose you could do something like:

    auto times = std::vector&lt;stop_watch::duration_t::rep&gt;();
    times.push_back(std::chrono::duration_cast&lt;stop_watch::duration_t&gt;(std::chrono::hours(1)).count());
    // same for other desired types...

    auto units = std::vector&lt;std::string&gt;();
    units.push_back("h ");
    // ...

    print_times(std::cout, sw.get_elapsed_time(), times, units);


So the times vector contains the time to use in the units of stop_watch::duration_t. And then you can use integer division to get the necessary values instead of duration_casting.


Other Things

If you're just measuring function times, you might not need the start / stop logic. You could perhaps simplify the class to something like the following:

class timer
{
public:

    using clock_t = std::chrono::high_resolution_clock;
    using duration_t = clock_t::duration;

private:

    clock_t::time_point start_time;

public:

    timer():
        start_time(clock_t::now()) { }

    duration_t get_elapsed_time() const { return (clock_t::now() - start_time); }

    void reset() { start_time = clock_t::now(); }
};


There's no need to worry about leaving the timer "running", since there's no actual work unless you query the time...

timer sw;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout &lt;&lt; "It took: " &lt;&lt; sw.get_elapsed_time().count() &lt;&lt; "units" &lt;&lt; std::endl;