c++ show time elapsed

To show the time elapsed in C++, you can use the <chrono> library. Here is an example code snippet that demonstrates how to accomplish this:

#include <iostream>
#include <chrono>

int main() {
    // Start the timer
    auto start = std::chrono::high_resolution_clock::now();

    // Perform some operations
    for (int i = 0; i < 1000000; ++i) {
        // Do something
    }

    // End the timer
    auto end = std::chrono::high_resolution_clock::now();

    // Calculate the duration
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();

    // Print the elapsed time
    std::cout << "Time elapsed: " << duration << " microseconds" << std::endl;

    return 0;
}

Let's go through each step of the code:

  1. Include the necessary libraries: In this case, we include <iostream> for input/output operations and <chrono> for time-related operations.

  2. Start the timer: We create a variable start of type std::chrono::time_point and assign it the current time using std::chrono::high_resolution_clock::now().

  3. Perform some operations: Here, we have a loop that performs some operations 1,000,000 times. This is just an example of some time-consuming task.

  4. End the timer: We create another variable end of type std::chrono::time_point and assign it the current time using std::chrono::high_resolution_clock::now().

  5. Calculate the duration: We calculate the duration between start and end using std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(). This gives us the duration in microseconds.

  6. Print the elapsed time: We use std::cout to print the elapsed time in microseconds.

  7. Return 0: Finally, we return 0 to indicate successful execution of the program.

This code will output the elapsed time in microseconds. You can modify it to display the time in a different unit if needed.