为了计算处理器时间,程序会使用两次不同的 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;
// Using pow function
time_req = clock();
for(int i=0; i<100000; i++)
{
y = log(pow(i,5));
}
time_req = clock() - time_req;
cout << "Using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
// Without pow function
time_req = clock();
for(int i=0; i<100000; i++)
{
y = log(i*i*i*i*i);
}
time_req = clock()- time_req;
cout << "Without using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
return 0;
}
运行程序后,输出将是
Using pow function, it took 0.014743 seconds Without using pow function, it took 0.001357 seconds
另请阅读