Created
March 4, 2022 07:54
-
-
Save neilbalch/1deea32c5918549572b7dd10a9c04d1f to your computer and use it in GitHub Desktop.
C++ Simple Scoped Timer
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> // cout | |
#include <string> // string | |
#include <chrono> // time_point, duration, microseconds | |
#include <thread> // this_Thread::sleep_for | |
template <typename Clock> | |
class ScopedTimer { | |
public: | |
ScopedTimer(const std::string& name) : name(name), start(Clock::now()) {} | |
~ScopedTimer() { | |
auto time = std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - start); | |
std::cout << "\"" << name << "\" took " << (time.count() / 1000.0) << "ms.\n"; | |
} | |
private: | |
const std::string& name; | |
const std::chrono::time_point<Clock> start; | |
}; | |
int main() { | |
ScopedTimer<std::chrono::high_resolution_clock> s("test"); | |
using namespace std::chrono_literals; | |
std::this_thread::sleep_for(1500ns); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment