C++clock()延时循环

时间:2023-03-09 18:49:45
C++clock()延时循环

函数clock(),返回程序开始执行后所用的系统时间,但是有两个复制问题。

  1.clock()返回时间的单位不一定是秒

  2.该函数的返回类型在某些系统上可能是Long,也可能是unsigned long或者其他类型。

头文件ctime提供了解决方案。

  1.首先定义了一个符号常量CLOCKS_PER_SEC,该常量等于每秒包含的系统单位数。因此,系统时间除以这个值,可以得到秒数。

  2.将秒数返回,乘以CLOCK_PER_SEC,可以得到以系统时间单位为单位的时间。

  3.ctime将clock_t作为clock()函数返回类型的别名,也就是将变量声明为clock_t类型。如  clock_t start=clock();

  eg:

#include<iostream>
#include<ctime>
int main(){
using namespace std;
cout<<"Enter the delay time,in secondes:";
float secs;
cin>>secs;
clock_t delay=secs * CLOCKS_PER_SEC;
cout<<"starting\a\n";
clock_t start=clock();
while(clock()-start<delay)
;
cout<<"done\a\n";
return ;
}

 该程序以系统时间为单位(而不是以秒为单位)计算延迟时间,避免了每轮循环中将系统时间转换为秒。