C++ Online Compiler
Example: Basic Code Timer in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Basic Code Timer #include <iostream> #include <chrono> // For timing utilities #include <thread> // For std::this_thread::sleep_for #include <vector> // For example task using namespace std; // User-defined material: A simple function that simulates work void simulateWork(int iterations) { long long sum = 0; for (int i = 0; i < iterations; ++i) { sum += i; } // To prevent compiler optimizing out the loop entirely if (sum == -1) { cout << "Impossible path." << endl; } } int main() { cout << "--- Basic Timing Example ---" << endl; // Step 1: Record the starting time auto start = chrono::high_resolution_clock::now(); // Step 2: Execute the user-defined material (our simulateWork function) cout << "Simulating work with 1,000,000 iterations..." << endl; simulateWork(1000000); // Call our function // Or, time a simple sleep // cout << "Sleeping for 100 milliseconds..." << endl; // this_thread::sleep_for(chrono::milliseconds(100)); // Step 3: Record the ending time auto end = chrono::high_resolution_clock::now(); // Step 4: Calculate the duration chrono::duration<double> duration = end - start; // Step 5: Output the duration in desired units (e.g., microseconds, milliseconds, seconds) // We can cast to specific duration types for cleaner output auto microseconds = chrono::duration_cast<chrono::microseconds>(duration); auto milliseconds = chrono::duration_cast<chrono::milliseconds>(duration); cout << "SimulateWork took: " << microseconds.count() << " microseconds." << endl; cout << "SimulateWork took: " << milliseconds.count() << " milliseconds." << endl; // Example with another task cout << "\nSimulating work with 50,000,000 iterations..." << endl; start = chrono::high_resolution_clock::now(); simulateWork(50000000); end = chrono::high_resolution_clock::now(); microseconds = chrono::duration_cast<chrono::microseconds>(end - start); cout << "SimulateWork took: " << microseconds.count() << " microseconds." << endl; return 0; }
Output
Clear
ADVERTISEMENTS