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;
}