Skip to content

Instantly share code, notes, and snippets.

@icorbrey
Created September 2, 2021 13:08
Show Gist options
  • Save icorbrey/40b15543d55b3000bf9f72c5cc17763b to your computer and use it in GitHub Desktop.
Save icorbrey/40b15543d55b3000bf9f72c5cc17763b to your computer and use it in GitHub Desktop.
High resolution timer for algorithm development
#include "timer.hpp"
using namespace std;
using namespace std::chrono;
timer::timer()
{
this->hasRun = false;
this->start = high_resolution_clock::now();
}
void timer::stop()
{
this->assert_timer_is_running();
this->end = high_resolution_clock::now();
this->hasRun = true;
}
unsigned int timer::nanoseconds()
{
this->assert_timer_is_stopped();
return duration_cast<chrono::nanoseconds>(this->end - this->start).count();
}
unsigned int timer::microseconds()
{
this->assert_timer_is_stopped();
return duration_cast<chrono::microseconds>(this->end - this->start).count();
}
unsigned int timer::milliseconds()
{
this->assert_timer_is_stopped();
return duration_cast<chrono::milliseconds>(this->end - this->start).count();
}
unsigned int timer::seconds()
{
this->assert_timer_is_stopped();
return duration_cast<chrono::seconds>(this->end - this->start).count();
}
void timer::assert_timer_is_running()
{
if (this->hasRun)
throw "Cannot stop timer that has already been stopped.";
}
void timer::assert_timer_is_stopped()
{
if (!this->hasRun)
throw "Cannot get elapsed time of still-running timer.";
}
#ifndef TIMER_HPP
#define TIMER_HPP
#include <chrono>
class timer
{
private:
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point end;
bool hasRun;
public:
timer();
void stop();
unsigned int nanoseconds();
unsigned int microseconds();
unsigned int milliseconds();
unsigned int seconds();
private:
void assert_timer_is_running();
void assert_timer_is_stopped();
};
#endif // !TIMER_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment