精准定时操作

// freq 是一秒内执行的次数
int freq_op(int freq)
{
    uint64_t freq_interval_ns = uint64_t(1000000000/freq)
    uint64_t start_time_ns = getTimeOfNs();
    uint64_t do_times_count = 0;
    while(true)
    {
        // do some thing
        do_times_count++;

        // 得到从开始到现在的运行总时间;计算睡眠时间
        uint64_t run_time_ns = getTimeOfNs() - start_time_ns;
        uint64_t do_times_should = uint64_t(run_time_ns/freq_interval_ns);
        if(do_times_count > do_times_should)
        {
            usleep((do_times_count - do_times_should) * freq_interval_ns - run_time_ns % freq_interval_ns);
        }
    }
}

posted @ 2021-02-09 10:14  delta1037  阅读(53)  评论(0编辑  收藏  举报