c++ measure time in microseconds

To measure time in microseconds in C++, you can use the <chrono> library. Here are the steps to do it:

  1. Include the <chrono> library at the beginning of your code:

cpp #include <chrono>

  1. Create a std::chrono::high_resolution_clock object to represent the clock:

cpp std::chrono::high_resolution_clock::time_point start; std::chrono::high_resolution_clock::time_point end;

  1. Use the now() function of the clock object to get the current time:

cpp start = std::chrono::high_resolution_clock::now();

  1. Perform the task for which you want to measure the time.

  2. After the task is completed, use the now() function again to get the current time:

cpp end = std::chrono::high_resolution_clock::now();

  1. Calculate the duration between the start and end times using the duration_cast function:

cpp auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

This line of code will give you the duration in microseconds.

Here's a complete example that measures the time taken to execute a simple loop:

#include <iostream>
#include <chrono>

int main() {
    std::chrono::high_resolution_clock::time_point start;
    std::chrono::high_resolution_clock::time_point end;

    start = std::chrono::high_resolution_clock::now();

    // Perform the task for which you want to measure the time
    for (int i = 0; i < 1000000; ++i) {
        // Do something
    }

    end = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

    std::cout << "Time taken: " << duration.count() << " microseconds" << std::endl;

    return 0;
}

This example measures the time taken to execute a loop that runs 1,000,000 times. The duration.count() function returns the duration in microseconds, which is then printed to the console.