linux下精确定时/控速的方法

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)