I have a friendly competition with couple of guys in the field of programming and recently we have become so interested in writing efficient code. Our challenge was to try t
Here's a little C++11 stopwatch I like to roll out when I need to time something:
#include
#include
template class basic_stopwatch
{
typedef T clock;
typename clock::time_point p;
typename clock::duration d;
public:
void tick() { p = clock::now(); }
void tock() { d += clock::now() - p; }
void reset() { d = clock::duration::zero(); }
template unsigned long long int report() const
{
return std::chrono::duration_cast(d).count();
}
unsigned long long int report_ms() const
{
return report();
}
basic_stopwatch() : p(), d() { }
};
struct c_clock
{
typedef std::clock_t time_point;
typedef std::clock_t duration;
static time_point now() { return std::clock(); }
};
template <> unsigned long long int basic_stopwatch::report_ms() const
{
return 1000. * double(d) / double(CLOCKS_PER_SEC);
}
typedef basic_stopwatch stopwatch;
typedef basic_stopwatch cstopwatch;
Usage:
stopwatch sw;
sw.tick();
run_long_code();
sw.tock();
std::cout << "This took " << sw.report_ms() << "ms.\n";
On any decent implementation, the default high_resolution_clock should give very accurate timing information.