how to check code execution time in visual studio c++
To check the code execution time in Visual Studio C++, you can use the std::chrono
library. Below are the steps to measure code execution time:
Step 1: Include the necessary headers
#include <iostream>
#include <chrono>
Step 2: Define the code to be measured
void myFunction() {
// Code to be measured
}
Step 3: Create variables to store start and end time
std::chrono::high_resolution_clock::time_point startTime, endTime;
Step 4: Capture the start time
startTime = std::chrono::high_resolution_clock::now();
Step 5: Call the code to be measured
myFunction();
Step 6: Capture the end time
endTime = std::chrono::high_resolution_clock::now();
Step 7: Calculate the duration
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count();
Step 8: Print the duration
std::cout << "Execution time: " << duration << " microseconds" << std::endl;
Here's a complete example that demonstrates the above steps:
#include <iostream>
#include <chrono>
void myFunction() {
// Code to be measured
for (int i = 0; i < 1000000; i++) {
// Some computation
}
}
int main() {
std::chrono::high_resolution_clock::time_point startTime, endTime;
startTime = std::chrono::high_resolution_clock::now();
myFunction();
endTime = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count();
std::cout << "Execution time: " << duration << " microseconds" << std::endl;
return 0;
}
This code measures the execution time of the myFunction
function. The std::chrono::high_resolution_clock
is used to capture the start and end time, and the std::chrono::duration_cast
is used to calculate the duration in microseconds. Finally, the duration is printed to the console.