C++ Code Timing: Measure Execution Time
In C++, you can use the following methods to measure the running time of code:
- “time”
- ultra high definition clock
- Obtain the current time with high precision using the high_resolution_clock.
- Obtain the current time using the high resolution clock.
- transforming the duration
- Calculate the difference between two time points, which is the running time of the code.
Here is an example code:
#include <iostream>
#include <chrono>
int main() {
// 获取开始时间点
auto start = std::chrono::high_resolution_clock::now();
// 执行代码
// ...
// 获取结束时间点
auto end = std::chrono::high_resolution_clock::now();
// 计算代码运行时间
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// 输出运行时间
std::cout << "代码运行时间: " << duration.count() << " 毫秒" << std::endl;
return 0;
}
Please note that using the high_resolution_clock class can provide higher precision time, but the accuracy of the results may vary depending on the system. In some cases, you may need to use other clock classes such as steady_clock or system_clock, depending on your specific needs.