Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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