Scoped Timer: Auto-Log Duration on Destruction
Scoped Timer: Auto-Log Duration on Destruction
In C++, managing resources and timing operations is crucial for performance optimization. This blog post will guide you through creating a Scoped Timer that automatically logs the duration of its scope when it is destroyed. This implementation leverages RAII (Resource Acquisition Is Initialization) principles to ensure clean and efficient code.
Content
Here's how you can implement a Scoped Timer in C++:
#include <iostream>
#include <chrono>
class ScopedTimer {
public:
explicit ScopedTimer(const std::string& name) : name(name), start(std::chrono::high_resolution_clock::now()) {}
~ScopedTimer() {
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "Duration of \"" << name << "\": " << duration << " ms" << std::endl;
}
private:
std::string name;
std::chrono::high_resolution_clock::time_point start;
};
int main() {
{
ScopedTimer timer("Example Scope");
// Your code here
} // Timer will log the duration when destroyed
return 0;
}
Conclusion
Creating a Scoped Timer in C++ that automatically logs the duration of its scope is a great way to measure and optimize performance. By using RAII principles, you can ensure that resources are properly managed and that timing information is logged without additional manual effort.