首页 > 解决方案 > CLOCK_MONOTONIC_RAW 分辨率与 CLOCK_MONOTONIC 不同,似乎太高了

问题描述

所以我刚刚测试了一个带有 2.6.31 内核的嵌入式系统上的可用时钟。

一些简单的测试代码:

#include <stdio.h>
#include <time.h>

int main(int argc, const char* argv[]) {
    struct timespec clock_resolution;

    printf("This system uses a timespec with %ldB in tv_sec and %ldB in tv_nsec.\n", (long)sizeof(clock_resolution.tv_sec), (long)sizeof(clock_resolution.tv_nsec));
    printf("An int is %ldB on this system, a long int is %ldB.\n", (long)sizeof(int), (long)sizeof(long));
    
    if (clock_getres(CLOCK_MONOTONIC, &clock_resolution))
        perror("Can't get CLOCK_MONOTONIC resolution time");
    printf("CLOCK_MONOTONIC has precision of %lds and %ldns on this system.\n", (long)clock_resolution.tv_sec, (long)clock_resolution.tv_nsec);
    
    if (clock_getres(CLOCK_MONOTONIC_RAW, &clock_resolution))
        perror("Can't get CLOCK_MONOTONIC_RAW resolution time");
    printf("CLOCK_MONOTONIC_RAW has precision of %lds and %ldns on this system.\n", (long)clock_resolution.tv_sec, (long)clock_resolution.tv_nsec);
    printf("Casted to unsigned this is %lus and %luns.\n", (unsigned long)clock_resolution.tv_sec, (unsigned long)clock_resolution.tv_nsec);

    return 0;
}

在 x86 主机上的 Ubuntu 20.04 (5.4.0-52) VM 上,它会导致:

This system uses a timespec with 8B in tv_sec and 8B in tv_nsec.
An int is 4B on this system, a long int is 8B.
CLOCK_MONOTONIC has precision of 0s and 1ns on this system.
CLOCK_MONOTONIC_RAW has precision of 0s and 1ns on this system.
Casted to unsigned this is 0s and 1ns.

在基于 ARM 的 NXP i.MX257 控制器上,它会导致:

This system uses a timespec with 4B in tv_sec and 4B in tv_nsec.
An int is 4B on this system, a long int is 4B.
CLOCK_MONOTONIC has precision of 0s and 1ns on this system.
CLOCK_MONOTONIC_RAW has precision of 0s and -1070597342ns on this system.
Casted to unsigned this is 0s and 3224369954ns.

这对我来说似乎有些不对劲!?作为ns-resolution为3224369954ns的无符号值,所以超过3s。

编辑以澄清一些事情:

标签: clinuxtime

解决方案


推荐阅读