run time calculator c++

To create a runtime calculator in C++, you will need to follow these steps:

  1. Include the necessary libraries: Start by including the necessary libraries for input/output operations (iostream) and for measuring time (chrono).
#include <iostream>
#include <chrono>
  1. Create a function to calculate the runtime: Next, create a function that performs the task for which you want to calculate the runtime. This function should take any necessary input parameters and return the result. For this example, let's create a simple function that calculates the sum of two numbers.
int calculateSum(int a, int b) {
    return a + b;
}
  1. Measure the start time: Before calling the function, measure the start time using the std::chrono library. This will allow us to calculate the runtime later.
auto startTime = std::chrono::high_resolution_clock::now();
  1. Call the function: Call the function you created in step 2, passing any necessary input parameters.
int result = calculateSum(5, 10);
  1. Measure the end time: After the function call, measure the end time using the std::chrono library.
auto endTime = std::chrono::high_resolution_clock::now();
  1. Calculate the runtime: Calculate the runtime by subtracting the start time from the end time. You can use the std::chrono::duration class to get the duration in seconds, milliseconds, or any other desired unit.
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count();
  1. Print the runtime: Finally, print the calculated runtime.
std::cout << "Runtime: " << duration << " microseconds" << std::endl;

Putting all the steps together, here's the complete code for a runtime calculator in C++:

#include <iostream>
#include <chrono>

int calculateSum(int a, int b) {
    return a + b;
}

int main() {
    auto startTime = std::chrono::high_resolution_clock::now();

    int result = calculateSum(5, 10);

    auto endTime = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count();

    std::cout << "Runtime: " << duration << " microseconds" << std::endl;

    return 0;
}

When you run this code, it will calculate the runtime of the calculateSum function and print the result in microseconds.