在C語言中,我們經常需要設置一個時間周期。在這里,我們通過Timeval結構實現時間周期的設置。首先,我們介紹timeval,其定義如下(轉載http://www.cnblogs.com/wainiwann/archive/2012/11/28/2792133.html):
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
#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, 不能實現其他動作。
歡迎大家指正!