服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C语言实现简单的定时器

C语言实现简单的定时器

2021-09-30 11:33研究猿小刘 C/C++

这篇文章主要为大家详细介绍了C语言实现简单的定时器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C语言实现简单的定时器的具体代码,供大家参考,具体内容如下

1.代码分析

C语言实现简单的定时器

2.代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
  }
  
 }
}

完整代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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();
}

C语言实现简单的定时器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_43225966/article/details/109250011

延伸 · 阅读

精彩推荐