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:
Include the necessary libraries: In this case, we include
<iostream>
for input/output operations and<chrono>
for time-related operations.Start the timer: We create a variable
start
of typestd::chrono::time_point
and assign it the current time usingstd::chrono::high_resolution_clock::now()
.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.
End the timer: We create another variable
end
of typestd::chrono::time_point
and assign it the current time usingstd::chrono::high_resolution_clock::now()
.Calculate the duration: We calculate the duration between
start
andend
usingstd::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
. This gives us the duration in microseconds.Print the elapsed time: We use
std::cout
to print the elapsed time in microseconds.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.