clock()函数
clock()函数返回程序开始执行后所用的时间。
头文件<ctime>与符号常量CLOCKS_PER_SEC
clock()函数的单位不是秒,并且函数的返回值类型不确定。因此在头文件<ctime>中定义了符号常量CLOCKS_PER_SEC,该常量等于每秒钟包含的系统时间单位数。
因此,利用clock() / CLOCK_PER_SEC可以计算程序执行了多少秒。 利用sec * CLOCK_PER_SEC可以计算sec秒包含多少个系统时间单位数。
clock_t类型
利用clock_t x = clock(),编译器可以将x转换为合适的类型。
计算程序运行时间
#include <iostream>
#include <ctime>
using namespace std
;
int main()
{
for(int j
= 1; j
<= 30; j
++)
for (int i
= 1; i
<= 12000000; i
++);
cout
<< double(clock()) / double(CLOCKS_PER_SEC
) << "s." << endl
;
return 0;
}
创建延迟循环
#include <iostream>
#include <ctime>
using namespace std
;
int main()
{
int x
= 0;
double sec
;
cin
>> sec
;
clock_t delay
= sec
* CLOCKS_PER_SEC
;
clock_t start
= clock();
while (clock() - start
< delay
)
x
++;
cout
<< "After " << sec
<< " s, x = " << x
<< ".\n";
return 0;
}