#include <chrono>
#include <ctime>
class Timer
{
public:
Timer() :running_(false),
has_run_at_least_once_(false)
{
}
virtual ~Timer()
{
}
virtual void Start()
{
if (!running())
{
start_cpu_ = std::chrono::high_resolution_clock::now();
running_ = true;
has_run_at_least_once_ = true;
}
}
virtual void Stop()
{
if (running())
{
stop_cpu_ = std::chrono::high_resolution_clock::now();
running_ = false;
}
}
virtual float Nanoseconds()
{
if (!has_run_at_least_once())
{
printf("Timer has never been run before reading time.");
return 0;
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(stop_cpu_ - start_cpu_).count();
}
virtual float MilliSeconds()
{
if (!has_run_at_least_once())
{
printf("Timer has never been run before reading time.");
return 0;
}
return std::chrono::duration_cast<std::chrono::milliseconds>(stop_cpu_ - start_cpu_).count();
}
virtual float MicroSeconds()
{
if (!has_run_at_least_once())
{
printf("Timer has never been run before reading time.");
return 0;
}
return std::chrono::duration_cast<std::chrono::microseconds>(stop_cpu_ - start_cpu_).count();
}
virtual float Seconds()
{
return MilliSeconds() / 1000.0;
}
inline bool running() { return running_; }
inline bool has_run_at_least_once() { return has_run_at_least_once_; }
private:
bool running_;
bool has_run_at_least_once_;
std::chrono::high_resolution_clock::time_point start_cpu_;
std::chrono::high_resolution_clock::time_point stop_cpu_;
};