C語言通過timeval結構設置周期


  在C語言中,我們經常需要設置一個時間周期。在這里,我們通過Timeval結構實現時間周期的設置。首先,我們介紹timeval,其定義如下(轉載http://www.cnblogs.com/wainiwann/archive/2012/11/28/2792133.html):

"timeval是一個結構體,在time.h中定義為:
struct timeval
{
     __time_t tv_sec;                /* Seconds. */
     __suseconds_t tv_usec;      /* Microseconds. */
};
其中,tv_sec為Epoch(1970-1-1零點零分)到創建struct timeval時的秒數,tv_usec為微秒數,即秒后面的零頭。"
 
Ok, 接下來我們通過如下代碼實現周期設置:
-------------------------------------------------------------------------------------------------------------------------------------------

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

int main()
{
int time_interval=3; // Set period to be 3s

printf("Testing start:\n");
while(1){
setPeriod(time_interval);
//You can add a method here to realize what you want to do in this period.
}
return 0;
}

void setPeriod(int time_interval){
static struct timeval tv1;
struct timeval tv2;
int time_in_us;
static int flag = 1;

gettimeofday(&tv2,NULL);

if(flag){
tv1.tv_sec = tv2.tv_sec;
tv1.tv_usec = tv2.tv_usec;
flag = 0;
return;
}

time_in_us = (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec - tv1.tv_usec;

if(time_in_us >= time_interval * 1000000) {
tv1.tv_sec = tv2.tv_sec;
tv1.tv_usec = tv2.tv_usec;
// You can add a method here to make statistic about the data you get in this peorid.
printf("Hello, world\n");
}
}

---------------------------------------------------------------------------------------------------------------------------------------------

以上代碼實現一個周期為3s的設置,執行結果為: 每隔三秒print一個“Hello world”.

注意,要實現每隔三秒print一個“Hello world”, sleep(3000) 會是一個更簡便的方法。但是,用sleep方法,那么在該周期三秒內,只能sleep, 不能實現其他動作。

歡迎大家指正!

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM