C++ Timing: Measure Code Execution

In C++, timing functionality can be implemented using the high_resolution_clock and time_point from the header file. The following is a simple example code:

#include <iostream>
#include <chrono>

int main() {
    auto start = std::chrono::high_resolution_clock::now();

    // 执行需要计时的代码
    for (int i = 0; i < 1000000; ++i) {
        // do something
    }

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> duration = end - start;

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

    return 0;
}

In this example, high_resolution_clock::now() is used to capture the current time point, then the code that needs to be timed is executed. Next, high_resolution_clock::now() is used again to capture the ending time point. The time difference between the two time points is then calculated, and the timing result is finally output.

bannerAds