Skip to content

Instantly share code, notes, and snippets.

@neilbalch
Created March 4, 2022 07:54
Show Gist options
  • Save neilbalch/1deea32c5918549572b7dd10a9c04d1f to your computer and use it in GitHub Desktop.
Save neilbalch/1deea32c5918549572b7dd10a9c04d1f to your computer and use it in GitHub Desktop.
C++ Simple Scoped Timer
#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