struct timespec begin;
unsigned long interval = xxxx;//nS
unsigned long long ns;
clock_gettime(CLOCK_MONOTONIC, &begin);
while(1)
{
.....
ns = begin.tv_nsec;
ns += interval;
begin.tv_sec += ns/(1000*1000*1000);
begin.tv_nsec = ns%(1000*1000*1000);
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &begin, NULL);
}
//优点是误差不累计,且不受系统负载影响
//缺点是相对复杂(对比usleep)linux下精确定时/控速的方法
最新推荐文章于 2025-07-28 22:36:32 发布
本文介绍了一种使用C/C++实现精确定时任务的方法,通过struct timespec和clock_gettime等函数控制任务的执行间隔,确保定时准确且不受系统负载影响。此方法虽然实现较为复杂,但能够有效避免累积误差。
1750

被折叠的 条评论
为什么被折叠?



