Automatic time complexity Calculator
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
void timeComplexityCalculator(int n) {
auto start = high_resolution_clock::now();
// O(1) complexity code snippet
int result = n * n;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken for O(1) complexity: " << duration.count() << " microseconds" << endl;
}
int main() {
int n;
cout << "Enter the input size: ";
cin >> n;
timeComplexityCalculator(n);
return 0;
}
This C++ code measures the execution time of an O(1) complexity code snippet. It uses the <chrono>
library to calculate the elapsed time between the start and stop moments of the code execution. The timeComplexityCalculator
function takes an integer n
as input, performs an operation that has constant time complexity (O(1)), and calculates the time taken for this operation to complete. In this specific case, it computes the square of the input n
. The main
function prompts the user to enter the input size, calls the timeComplexityCalculator
function with the input value, and displays the execution time in microseconds.