Last active
May 6, 2019 20:57
-
-
Save bwedding/84d1d3118cb8d3c64d3613cc26b78ad1 to your computer and use it in GitHub Desktop.
High resolution, pure C++, auto-ranging execution timer. See examples in main(). This is modified slightly from the code by Code Blacksmith on Youtube
This file contains hidden or 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
// ExecutionTimer.cpp | |
// original code by Code Blacksmith on Youtube | |
// https://www.youtube.com/watch?v=GV0JMHOpoEw | |
#include "stdafx.h" // remove if not needed | |
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
#include <chrono> | |
using namespace std::chrono; | |
class ExecutionTimer | |
{ | |
public: | |
// Use the best steady clock available | |
using Clock = std::conditional_t<high_resolution_clock::is_steady, | |
high_resolution_clock, | |
steady_clock>; | |
ExecutionTimer() = default; | |
inline ~ExecutionTimer() | |
{ | |
std::string units = " microSeconds"; | |
// Determine whether to print uSecs or mSecs or Secs | |
double count = duration_cast<microseconds>(Clock::now() - mStart).count(); | |
if (count > 1000) | |
{ | |
// Convert to milliseconds | |
units = " milliSeconds"; | |
count /= 1000.0f; | |
if (count > 1000) | |
{ | |
// Convert to seconds | |
units = " Seconds"; | |
count /= 1000.0f; | |
} | |
} | |
std::cout | |
<< "Elapsed: " << count << units.data() << std::endl; | |
} | |
private: | |
Clock::time_point mStart = Clock::now(); | |
}; | |
int main() | |
{ | |
volatile double x = 2.0; | |
{ | |
// test uSec output | |
ExecutionTimer timer; | |
for (int i = 1; i < 1000; i++) | |
for (int j = 1; j < 10; j++) | |
x *= j; | |
} | |
{ | |
// test mSec output | |
ExecutionTimer timer; | |
for (int i = 1; i < 200000; i++) | |
for (int j = 1; j < 100; j++) | |
x *= j; | |
} | |
{ | |
// test seconds output | |
ExecutionTimer timer; | |
for (int i = 1; i < 1000000; i++) | |
for (int j = 1; j < 1000; j++) | |
x *= j; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment