Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This class was written with the intention of simplifying the timing of code segments, but to remain generic in terms of what clock and time representation.

#include <chrono>

template<typename C>
class stop_watch
{
    std::chrono::time_point<C> start;

public:
    stop_watch() : start(C::now()) {}

    template<typename U>
    typename U::rep elapsed() const
    {
        return std::chrono::duration_cast<U>(C::now() - start).count();
    }

    void reset()
    {
        start = C::now();
    }
};

Use it like so:

#include <iostream>
#include <thread>

using namespace std;

int main()
{
    stop_watch<chrono::high_resolution_clock> sw;

    this_thread::sleep_for(chrono::seconds(1));

    cout << sw.elapsed<chrono::seconds>() << endl;  // Prints "1".

    sw.reset();

    this_thread::sleep_for(chrono::seconds(1));

    cout << sw.elapsed<chrono::milliseconds>() << endl; // Prints "1000".

    return 0;
}
share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.