C语言实现简单的定时器

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C语言实现简单的定时器

研究猿小刘   2020-10-29 我要评论

1.代码分析

2.代码

#include <stdio.h>
#include <time.h>
#include <conio.h>

#ifndef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC 1000
#endif

int main( void )
{
 clock_t start;
 long count = 1;
 start = clock();
 while(1)
 {
 if((clock() - start) == CLOCKS_PER_SEC)
 {
 printf("%ld\n",count++);
 start = clock();
 //break;
 }
 }
 getch();
}

3. 代码抽象出一个定时器函数 void timer(long time)

void timer(long time){

 clock_t start;
 long count = 1;
 start = clock();
 while(1)
 {
 if((clock() - start) != (time*CLOCKS_PER_SEC))
 {
 //时间没有到,啥也不做,空循环
 }else {
   //时间到了退出循环
   // printf("%s","hello");
   break;
  }
  
 }
}

完整代码

#include <stdio.h>
#include <time.h>
#include <conio.h>

#ifndef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC 1000
#endif
/**
 * time 的单位为s
 */
void timer(long time){

 clock_t start;
 long count = 1;
 start = clock();
 while(1)
 {
 if((clock() - start) != (time*CLOCKS_PER_SEC))
 {
 //时间没有到,啥也不做,空循环
 }else {
   //时间到了退出循环
   // printf("%s","hello");
   break;
  }
  
 }
}
int main( void )
{
 
 for(int i=0;i<10;i++){
  timer(1);
  printf("%d\n",i);
 }
 getch();
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们