What is the usage of the clock function in C++?

In C++, the clock() function can be used to retrieve the running time of a program, returning the amount of CPU time the program has occupied since it started until the clock() function is called. The clock() function returns clock ticks, measured in units of clock_t, which is an integer type. While the standard unit for clock_t is seconds, the actual implementation may vary.

Here is an example code using the clock() function to calculate the running time of a program.

#include <iostream>
#include <ctime>

int main() {
    clock_t start, end;
    start = clock(); // 记录开始时间

    // 执行一些耗时操作
    for (int i = 0; i < 100000000; ++i) {
        // do something
    }

    end = clock(); // 记录结束时间

    double duration = (double)(end - start) / CLOCKS_PER_SEC; // 计算程序运行时间,单位为秒

    std::cout << "程序运行时间为:" << duration << " 秒" << std::endl;

    return 0;
}

It is important to note that the clock() function is not thread-safe, and if multiple threads in a program call the clock() function simultaneously, it may result in unpredictable behavior. It is recommended to use libraries in C++11 for measuring time in a multi-threaded environment.

Leave a Reply 0

Your email address will not be published. Required fields are marked *