C語言實現(xiàn)簡單的定時器
更新時間:2020年10月29日 12:54:59 作者:研究猿小劉
這篇文章主要為大家詳細介紹了C語言實現(xiàn)簡單的定時器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言實現(xiàn)簡單的定時器的具體代碼,供大家參考,具體內(nèi)容如下
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. 代碼抽象出一個定時器函數(shù) 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))
{
//時間沒有到,啥也不做,空循環(huán)
}else {
//時間到了退出循環(huán)
// 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))
{
//時間沒有到,啥也不做,空循環(huán)
}else {
//時間到了退出循環(huán)
// printf("%s","hello");
break;
}
}
}
int main( void )
{
for(int i=0;i<10;i++){
timer(1);
printf("%d\n",i);
}
getch();
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Qt數(shù)據(jù)庫應(yīng)用之實現(xiàn)圖片轉(zhuǎn)pdf
這篇文章主要為大家詳細介紹了如何利用Qt實現(xiàn)圖片轉(zhuǎn)pdf功能,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定參考價值,需要的可以了解一下2022-06-06
C++類與對象深入之引用與內(nèi)聯(lián)函數(shù)與auto關(guān)鍵字及for循環(huán)詳解
朋友們好,這篇播客我們繼續(xù)C++的初階學(xué)習(xí),現(xiàn)在對一些C++的入門知識做了些總結(jié),整理出來一篇博客供我們一起復(fù)習(xí)和學(xué)習(xí),如果文章中有理解不當?shù)牡胤?還希望朋友們在評論區(qū)指出,我們相互學(xué)習(xí),共同進步2022-06-06
Qt實現(xiàn)編輯數(shù)據(jù)庫數(shù)據(jù)的方法詳解
這篇文章主要為大家詳細介紹了Qt是如何實現(xiàn)編輯數(shù)據(jù)庫數(shù)據(jù)的,文中的示例代碼簡潔易懂,對我們深入了解QT有一定的幫助,感興趣的小伙伴可以了解一下2023-02-02

