寻找周期c语言,C语言通过timeval结构设置周期

本文展示了一个使用C语言实现的简单程序,该程序能够每3秒钟打印一次“Hello, world”。通过获取当前时间和上一周期的时间进行比较,确保每个周期的准确执行时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include

#include

#include

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

欢迎大家指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值