首页 技术 正文
技术 2022年11月8日
0 收藏 651 点赞 1,868 浏览 1463 个字

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

欢迎大家指正!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,565
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905