C++ Online Compiler
Example: Reusable Timer Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Reusable Timer Function #include <iostream> #include <chrono> #include <functional> // For std::function #include <vector> #include <numeric> // For std::iota using namespace std; // User-defined material: Function to sum elements of a vector long long sumVectorElements(const vector<int>& vec) { long long sum = 0; for (int x : vec) { sum += x; } return sum; } // Reusable timing function template <typename Func> chrono::microseconds measureExecutionTime(Func func) { auto start = chrono::high_resolution_clock::now(); func(); // Execute the passed function auto end = chrono::high_resolution_clock::now(); return chrono::duration_cast<chrono::microseconds>(end - start); } int main() { cout << "--- Reusable Timer Function Example ---" << endl; vector<int> numbers(1000000); iota(numbers.begin(), numbers.end(), 0); // Fill with 0, 1, ..., 999999 // Timing sumVectorElements directly cout << "Timing sumVectorElements..." << endl; chrono::microseconds duration_sum_vec = measureExecutionTime([&]() { long long result = sumVectorElements(numbers); // Avoid optimizing out result by potentially using it if (result == -1) { /* dead code */ } }); cout << "sumVectorElements took: " << duration_sum_vec.count() << " microseconds." << endl; // Timing a lambda that performs some other task cout << "\nTiming a custom lambda (vector sorting)..." << endl; vector<int> random_numbers = {5, 2, 9, 1, 7, 3, 8, 4, 6, 0}; chrono::microseconds duration_sort = measureExecutionTime([&]() { sort(random_numbers.begin(), random_numbers.end()); }); cout << "Sorted vector in: " << duration_sort.count() << " microseconds." << endl; return 0; }
Output
Clear
ADVERTISEMENTS