C++ Online Compiler
Example: RAII Timer Class in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// RAII Timer Class #include <iostream> #include <chrono> #include <thread> // For std::this_thread::sleep_for #include <string> // For message using namespace std; class ScopedTimer { public: explicit ScopedTimer(const string& message) : m_message(message), m_start(chrono::high_resolution_clock::now()) { // Optional: print start message // cout << "Timer '" << m_message << "' started." << endl; } ~ScopedTimer() { auto end = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(end - m_start); cout << "Timer '" << m_message << "' finished in " << duration.count() << " microseconds." << endl; } private: string m_message; chrono::high_resolution_clock::time_point m_start; }; // User-defined material: A function to simulate complex calculations void complexCalculation(int seconds) { long long result = 0; for (int i = 0; i < seconds * 100000; ++i) { // Simulate work for 'seconds' result += i * i; } // Prevent optimization if (result == -1) { /* dead code */ } this_thread::sleep_for(chrono::seconds(seconds)); // Ensure visible duration } int main() { cout << "--- RAII Timer Class Example ---" << endl; cout << "Starting main tasks..." << endl; // Task 1: Scoped timer for a block of code { ScopedTimer timer_block("Complex Loop"); cout << "Inside complex loop block..." << endl; for (int i = 0; i < 500000; ++i) { // Some heavy computation volatile int temp = i * i; // Use volatile to prevent optimization if (temp % 100000 == 0) { // cout << "." << flush; // Optional progress indicator } } cout << "Exiting complex loop block." << endl; } // timer_block goes out of scope here, duration is printed cout << "\nContinuing with other tasks..." << endl; // Task 2: Scoped timer for a function call { ScopedTimer timer_function("Function Call (complexCalculation)"); complexCalculation(1); // Call our user-defined function } // timer_function goes out of scope here cout << "\nMain tasks completed." << endl; return 0; }
Output
Clear
ADVERTISEMENTS