C语言实现简单的定时器

Thalia ·
更新时间:2024-09-20
· 685 次阅读

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

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(); }

您可能感兴趣的文章:c语言定时器示例分享vc6.0中c语言控制台程序中的定时技术(定时器)



C语言 定时器

需要 登录 后方可回复, 如果你还没有账号请 注册新账号