RAII scope timer for quick profiling
C++
#include <chrono>
#include <iostream>
#include <string>
#include <utility>
// Prints how long its scope took; copies are blocked so it fires exactly once.
class ScopeTimer {
public:
explicit ScopeTimer(std::string label)
: label_(std::move(label)), start_(std::chrono::steady_clock::now()) {}
ScopeTimer(const ScopeTimer&) = delete;
ScopeTimer& operator=(const ScopeTimer&) = delete;
~ScopeTimer() {
const auto elapsed = std::chrono::steady_clock::now() - start_;
const auto micros = std::chrono::duration_cast<std::chrono::microseconds>(elapsed);
std::cout << label_ << " took " << micros.count() << " us\n";
}
private:
std::string label_;
std::chrono::steady_clock::time_point start_;
};
int main() {
long total = 0;
{
ScopeTimer timer("sum loop");
for (long i = 0; i < 1000000; ++i) {
total += i;
}
}
std::cout << total << '\n';
}