在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, 不能实现其他动作。

欢迎大家指正!

 

 

 

 

posted on 2015-12-20 23:42  飞行的俊哥  阅读(8770)  评论(0编辑  收藏  举报