标签:
在C语言中,我们经常需要设置一个时间周期。在这里,我们通过Timeval结构实现时间周期的设置。首先,我们介绍timeval,其定义如下(转载http://www.cnblogs.com/wainiwann/archive/2012/11/28/2792133.html):
#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, 不能实现其他动作。
欢迎大家指正!
标签:
原文地址:http://www.cnblogs.com/biggerjun2015/p/5062234.html