c语言中怎么设置计时器?

c语言中设置计时器怎么编写源代码?例如:每格5秒输出字符a。
没看懂啊,能不能写的完整一点?多谢!

#include <iostream>  

#include <time.h>    

using namespace std;  

int main()  

{  

clock_t start = clock();    

//do some process here    

clock_t end = (clock() - start)/CLOCKS_PER_SEC;  

cout<<"time comsumption is "<<end<<endl;  

}

扩展资料

使用linux的系统设置计时器

#include <sys/time.h>  

int main()  

{  

timeval starttime,endtime;  

gettimeofday(&starttime,0);    

//do some process here    

gettimeofday(&endtime,0);  

double timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - startime.tv_usec;  

timeuse /=1000;//除以1000则进行毫秒计时,如果除以1000000则进行秒级别计时,如果除以1则进行微妙级别计时  

}    

timeval的结构如下:  

strut timeval  

{  

long tv_sec; /* 秒数 */  

long tv_usec; /* 微秒数 */  

};

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-12-16
  C语言计时可以用很多方法。
  
  1. 如果是想使用秒级别的技术,可用使用C语言库<time.h>自带的clock()进行计时。如:
  
  #include <iostream>
  #include <time.h>
  
  using namespace std;
  int main()
  {
  clock_t start = clock();
  
  //do some process here
  
  clock_t end = (clock() - start)/CLOCKS_PER_SEC;
  cout<<"time comsumption is "<<end<<endl;
  }
  
  以上方法只能用于秒级别的计时。
  
  2.如果想使用毫秒级别的计时可以使用2种方法。一种是使用linux的系统库<sys/time.h>,一种是使用CUDA的cutil的库。
  
  A. 如果使用linux的系统库,则可以使用如下方法:
  
  #include <sys/time.h>
  int main()
  {
  timeval starttime,endtime;
  gettimeofday(&starttime,0);
  
  //do some process here
  
  gettimeofday(&endtime,0);
  double timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - startime.tv_usec;
  timeuse /=1000;//除以1000则进行毫秒计时,如果除以1000000则进行秒级别计时,如果除以1则进行微妙级别计时
  }
  
  timeval的结构如下:
  strut timeval
  {
  long tv_sec; /* 秒数 */
  long tv_usec; /* 微秒数 */
  };
  
  上述方法可以进行微妙级别的计时,当然也可以进行毫秒和秒的计时。
  
  B. 如果可以使用CUDA的话,则可以使用CUDA的sdk里面的cutil库里面的函数。
  #include <cutil.h>
  int main()
  {
  unsigned int timer = 0;
  cutCreatTimer(&timer);//创建计时器
  cutStartTimer(&timer);//开始计时
  
  // do some process here
  
  cutStopTimer(&timer);//停止计时
  cout<<"time is "<<cutGetTimerValue(&timer)<<endl;//打印时间
  }
  本回答被网友采纳
第2个回答  2005-12-06
//无窗口计时器
VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg,UINT_PTR idEvent,DWORD dwTime)
{
//定时调用
}

SetTimer(NULL,NULL,20,TimerProc);//20是时间的间隔
第3个回答  2005-12-06
while(true)
{
Sleep(1000)
cout<<"a"<<endl;
}

附加说明一下:以上只是示例程序,由于WIN32程序是信息驱动,象VC里面的TIMER,建立在WINDOWS消息循环上的,在C语言设置定时器,不是十分好做.
如上面可以这样写:
int t1,t2;
t1=getcurrenttime();
while(true)
{
GetTime(&t2);
if(t1-t2>=5)
{
处理代码
cout<<"a"<<endl;
t1=t2;
}

}
相似回答