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:
- Include the
<chrono>
library at the beginning of your code:
cpp
#include <chrono>
- 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;
- Use the
now()
function of the clock object to get the current time:
cpp
start = std::chrono::high_resolution_clock::now();
Perform the task for which you want to measure the time.
After the task is completed, use the
now()
function again to get the current time:
cpp
end = std::chrono::high_resolution_clock::now();
- 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.