Last active
January 13, 2016 18:13
-
-
Save ryanbartley/9c1c5314872b94807e27 to your computer and use it in GitHub Desktop.
Timer Impl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
namespace cinder { | |
// nanoseconds Alias | |
using nanoseconds = std::chrono::nanoseconds; | |
/** \brief A high-resolution timer class **/ | |
class Timer { | |
using clock = std::chrono::high_resolution_clock; | |
public: | |
//! Constructs a default timer which is initialized as stopped | |
Timer(); | |
//! Constructs a default timer which is initialized as running unless \a startOnConstruction is false | |
Timer( bool startOnConstruction ); | |
//! Begins timing. Optional \a offsetSeconds parameter allows a relative offset | |
void start( nanoseconds offset = nanoseconds( 0 ) ); | |
//! Resumes timing without resetting the timer. | |
void resume(); | |
//! Ends timing | |
void stop(); | |
//! Returns the elapsed seconds if the timer is running, or the total time between calls to start() and stop() if it is stopped. | |
double getSeconds() const; | |
//! Returns nanosecond type from chrono of the elapsed ticks from the system clock. | |
nanoseconds getElapsedTicks() const; | |
//! Returns whether the timer is currently running | |
bool isStopped() const { return !mIsRunning; } | |
private: | |
clock::time_point mStartTime; | |
clock::duration mCurrentDuration; | |
bool mIsRunning; | |
}; | |
inline Timer::Timer() | |
: mIsRunning( false ), mCurrentDuration( 0 ) | |
{ | |
} | |
inline Timer::Timer( bool startOnConstruction ) | |
: mIsRunning( false ), mCurrentDuration( 0 ) | |
{ | |
if( startOnConstruction ) | |
start(); | |
} | |
inline void Timer::start( nanoseconds offset ) | |
{ | |
mStartTime = clock::now(); | |
mCurrentDuration = offset; | |
mIsRunning = true; | |
} | |
inline void Timer::resume() | |
{ | |
if( mIsRunning ) | |
return; | |
mStartTime = clock::now(); | |
mIsRunning = true; | |
} | |
inline void Timer::stop() | |
{ | |
if( ! mIsRunning ) | |
return; | |
mIsRunning = false; | |
mCurrentDuration += (clock::now() - mStartTime); | |
} | |
inline nanoseconds Timer::getElapsedTicks() const | |
{ | |
if( ! mIsRunning ) | |
return mCurrentDuration; | |
else | |
return mCurrentDuration + (clock::now() - mStartTime); | |
} | |
inline double Timer::getSeconds() const | |
{ | |
return getElapsedTicks().count() * 0.000000001; | |
} | |
} // namespace cinder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment