Last active
March 27, 2024 02:42
-
-
Save mcleary/b0bf4fa88830ff7c882d to your computer and use it in GitHub Desktop.
C++ Timer using std::chrono
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 <iostream> | |
#include <chrono> | |
#include <ctime> | |
#include <cmath> | |
class Timer | |
{ | |
public: | |
void start() | |
{ | |
m_StartTime = std::chrono::system_clock::now(); | |
m_bRunning = true; | |
} | |
void stop() | |
{ | |
m_EndTime = std::chrono::system_clock::now(); | |
m_bRunning = false; | |
} | |
double elapsedMilliseconds() | |
{ | |
std::chrono::time_point<std::chrono::system_clock> endTime; | |
if(m_bRunning) | |
{ | |
endTime = std::chrono::system_clock::now(); | |
} | |
else | |
{ | |
endTime = m_EndTime; | |
} | |
return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - m_StartTime).count(); | |
} | |
double elapsedSeconds() | |
{ | |
return elapsedMilliseconds() / 1000.0; | |
} | |
private: | |
std::chrono::time_point<std::chrono::system_clock> m_StartTime; | |
std::chrono::time_point<std::chrono::system_clock> m_EndTime; | |
bool m_bRunning = false; | |
}; | |
long fibonacci(unsigned n) | |
{ | |
if (n < 2) return n; | |
return fibonacci(n-1) + fibonacci(n-2); | |
} | |
int main() | |
{ | |
// std::chrono::time_point<std::chrono::system_clock> start, end; | |
// start = std::chrono::system_clock::now(); | |
// Timer timer; | |
// timer.start(); | |
// std::cout << "f(42) = " << fibonacci(42) << '\n'; | |
// timer.stop(); | |
// | |
// std::cout << "Time: " << timer.elapsed() << std::endl; | |
// end = std::chrono::system_clock::now(); | |
// std::chrono::duration<double> elapsed_seconds = end-start; | |
// std::time_t end_time = std::chrono::system_clock::to_time_t(end); | |
// std::cout << "finished computation at " << std::ctime(&end_time) | |
// << "elapsed time: " << elapsed_seconds.count() << "s\n"; | |
Timer timer; | |
timer.start(); | |
int counter = 0; | |
double test, test2; | |
while(timer.elapsedSeconds() < 10.0) | |
{ | |
counter++; | |
test = std::cos(counter / M_PI); | |
test2 = std::sin(counter / M_PI); | |
} | |
timer.stop(); | |
std::cout << counter << std::endl; | |
std::cout << "Seconds: " << timer.elapsedSeconds() << std::endl; | |
std::cout << "Milliseconds: " << timer.elapsedMilliseconds() << std::endl | |
; | |
} |
This is a stopwatch not a timer.
This is a stopwatch not a timer.
Thanks for the clarification
"Thanks for the clarification"
proceeds to keep the name
It's a distinction without a difference.
There's no reason to change it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better use std::chrono::steady_clock, because the system time (used by system_clock) can be adjusted at any moment.