Skip to content

Instantly share code, notes, and snippets.

@AJLeuer
Last active September 18, 2015 07:22
Show Gist options
  • Save AJLeuer/82489bd29182f064c79f to your computer and use it in GitHub Desktop.
Save AJLeuer/82489bd29182f064c79f to your computer and use it in GitHub Desktop.
C++ timer class
#include "Timer.hpp"
using namespace std ;
Timer::Timer() : timerStarted(false) {}
Timer::Timer(Timer && other) : timerStarted(std::move(other.timerStarted)), start(std::move(other.start)) {}
Timer::~Timer() {}
Timer & Timer::operator=(Timer && rhs) {
if (this != &rhs) {
timerStarted = rhs.timerStarted ;
start = std::move(rhs.start) ;
}
return *this ;
}
void Timer::startTimer() {
if (timerStarted) {
cerr << "stopTimer() must be called before startTimer() can be called again for this Timer object \n" ;
throw exception() ;
}
timerStarted = true ;
start = chrono::steady_clock::now() ;
}
std::chrono::nanoseconds Timer::checkTimeElapsed() {
//returns in micro or nanoseconds
if (!timerStarted) {
cerr << "checkTimeElapsed() can only be called after startTimer() has been called once \n" ;
throw exception() ;
}
auto duration = chrono::steady_clock::now() - start ;
return duration ;
}
void Timer::reset() {
start = chrono::steady_clock::now() ;
}
std::chrono::nanoseconds Timer::stopTimer() {
if (!timerStarted) {
cerr << "stopTimer() can only be called after startTimer() has been called once \n" ;
throw exception() ;
}
auto duration = chrono::steady_clock::now() - start ;
timerStarted = false ;
return duration ;
}
//
// ClockTicks.h
// Intro to C++
//
// Created by Adam J. Leuer on 7/27/13.
// Copyright (c) 2013 Adam J. Leuer. All rights reserved.
//
#ifndef __Time__
#define __Time__
#include <iostream>
#include <chrono>
using namespace std ;
/**
* @brief A class providing simple nanosecond-precision timing facilities
*/
class Timer {
private:
bool timerStarted ;
chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> start ;
public:
Timer() ;
Timer(Timer && other) ;
~Timer() ;
Timer & operator=(Timer && rhs) ;
/**
* @brief Starts the timer.
*/
void startTimer() ;
/**
* @brief Checks the time elapsed since startTimer() was called.
* Unlike stopTimer(), this function will not stop the timer.
*
* @note 1 millisecond = 1000000 nanoseconds
*
* @return The time elapsed in nanoseconds.
*/
std::chrono::nanoseconds checkTimeElapsed() ;
/**
* @brief Resets the timer to 0
*/
void reset() ;
/**
* @brief Stops timer and returns the time elapsed since startTimer() was called.
*
* @note 1 millisecond = 1000000 nanoseconds
*
* @return The time elapsed in nanoseconds.
*/
std::chrono::nanoseconds stopTimer() ;
} ;
#endif /* defined Time */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment