Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kevinkreiser
Last active March 20, 2019 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinkreiser/7683b979155134e8eda0908b4b716280 to your computer and use it in GitHub Desktop.
Save kevinkreiser/7683b979155134e8eda0908b4b716280 to your computer and use it in GitHub Desktop.
timer that fires a callback with the elapsed duration when going out of scope
//Try this out like so:
//g++ -std=c++14 scoped_timer.cpp -o scoped_timer && ./scoped_timer
#include <chrono>
#include <functional>
#include <thread>
#include <iostream>
template <typename clock_t = std::chrono::steady_clock>
struct scoped_timer {
using duration_t = typename clock_t::duration;
const std::function<void(const duration_t&)> callback;
const std::chrono::time_point<clock_t> start;
scoped_timer(const std::function<void(const duration_t&)>& finished_callback) :
callback(finished_callback), start(clock_t::now()) { }
scoped_timer(std::function<void(const duration_t&)>&& finished_callback) :
callback(finished_callback), start(clock_t::now()) { }
~scoped_timer() { callback(clock_t::now() - start); }
};
void test(bool should_throw) {
scoped_timer<> t([](const scoped_timer<>::duration_t& elapsed) {
auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
std::cout << "took " << e << "ms" << std::endl;
});
std::this_thread::sleep_for(std::chrono::seconds(1));
if (should_throw)
throw nullptr;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
struct slacker {
void show_slack(const std::chrono::steady_clock::duration& elapsed) {
auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
std::cout << "took " << e << "ms" << std::endl;
}
void slack_off() {
scoped_timer<> t(std::bind(&slacker::show_slack, this, std::placeholders::_1));
std::this_thread::sleep_for(std::chrono::seconds(3));
}
};
int main(void) {
try {
test(false);
test(true);
}
catch(...){}
slacker s;
s.slack_off();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment