Linux C时间

获取时间

/* 获取NS时间 -9 */
static uint64_t getTimeOfNs() {
    struct timespec tv;
    clock_gettime(CLOCK_REALTIME, &tv);
    return tv.tv_sec*1000000000 + tv.tv_nsec;
}

/* 获取MS时间 -3 */
uint64_t get_time_of_ms()
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    return tv.tv_sec * (uint64_t)1000 + tv.tv_usec / 1000;
}

精确睡眠

/* 精确睡眠US时间 */
static void sleepUS(uint64_t usec){
    struct timeval tv;
    tv.tv_sec = usec / 1000000UL;
    tv.tv_usec = usec % 1000000UL;
    errno = 0;
    select(0, 0, 0, NULL, &tv);
    if (errno != 0){
        // error
    }
}

按照指定频率执行

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)
        {
            // 用到了上面精确睡眠的函数
            sleepUS((do_times_count - do_times_should) * freq_interval_ns -  - run_time_ns % freq_interval_ns);
        }
    }
}

秒转换为时间字符串

/* 将时间秒计数转换成 dd:hh:mm:ss的格式 */
void scaleDownTime(uint64_t s_time, std::string &time)
{
    char buffer[128];
    int d = 0;
    int h = 0;
    int m = 0;
    int s = 0;

    if(s_time >= 3600 * 24){
        d = s_time / (3600 * 24);
        s_time = s_time % (3600 * 24);
    }

    if(s_time >= 3600){
        h = s_time / 3600;
        s_time = s_time % 3600;
    }

    if(s_time >= 60){
        m = s_time / 60;
        s_time = s_time % 60;
    }
    s = s_time;
    if(d > 0){
        int size = snprintf(buffer, 128, "%dd %02d:%02d:%02d", d, h, m, s);
        buffer[size] = '\0';
    }else{
        int size = snprintf(buffer, 128, "%02d:%02d:%02d", h, m, s);
        buffer[size] = '\0';
    }
    time = std::string(buffer);
}

你可能感兴趣的:(Linux C时间)