C語言實現簡單的定時器
阿新 • • 發佈:2020-10-30
本文例項為大家分享了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(); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。