跳到主要内容

C++ clock() 函数

为了计算处理器时间,通常使用两次对 clock() 的不同调用所返回的值之间的差值,一次在程序开始时,另一次在程序结束时。为了将值转换为秒,需要将其除以宏 CLOCKS_PER_SEC

clock() 时间可能比实际的墙钟时间快或慢。这取决于操作系统如何分配进程的资源。

如果处理器被其他进程共享,clock() 时间可能比墙钟时间慢。而如果当前进程在多线程系统中执行,clock() 时间可能比墙钟时间快。

clock() 函数原型

clock_t clock();

它定义在 <ctime> 头文件中。

clock() 参数

clock() 返回值

  • 成功时,clock() 函数返回程序到目前为止使用的处理器时间。
  • 失败时,返回 -1,该值被转换为 clock_t 类型。

示例:clock() 函数如何工作

#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;

int main ()
{
float x,y;
clock_t time_req;

// 使用 pow 函数
time_req = clock();
for(int i=0; i<100000; i++)
{
y = log(pow(i,5));
}
time_req = clock() - time_req;
cout << "使用 pow 函数,耗时 " << (float)time_req/CLOCKS_PER_SEC << " 秒" << endl;

// 不使用 pow 函数
time_req = clock();
for(int i=0; i<100000; i++)
{
y = log(i*i*i*i*i);
}
time_req = clock()- time_req;
cout << "不使用 pow 函数,耗时 " << (float)time_req/CLOCKS_PER_SEC << " 秒" << endl;

return 0;
}

当你运行程序时,输出将是:

使用 pow 函数,耗时 0.014743

不使用 pow 函数,耗时 0.001357