国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > timespec_getres 以获得更好的体验。

# C 语言标准库函数 timespec_getres

在头文件 time.h 中定义。
/*********************************************
 * @brief 根据时间基准获取时间分辨率
 * @param ts 返回时间分辨率
 * @param base 时间基准
 * @return 是(0)否(非 0)成功
 ********************************************/
int timespec_getres(struct timespec* ts, int base);

!subtitle:说明

检查时间基准 base 是否有效,如果有效则获取 timespec_get 在该基准下的时间分辨率。

!subtitle:参数

  • ts - 返回时间分辨率,可以为 NULL

  • base - 时间基准,例如 TIME_UTC

!subtitle:返回值

  • base 有效时返回 base

  • base 无效时返回 0

# 示例

#include <stdio.h>
#include <time.h>
 
int main(void)
{
    struct timespec ts;
    if (timespec_getres(&ts, TIME_UTC) == 0)
    {
        printf("时间基准 TIME_UTC 无效");
    }
    else
    {
        printf("时间基准 TIME_UTC 的时间分辨率为 %ld 纳秒\n", ts.tv_nsec);
    }
    
    return 0;
}

运行结果:

时间基准 TIME_UTC 的时间分辨率为 1 纳秒

# 推荐阅读

# 参考标准

  • C23 standard (ISO/IEC 9899:2024):

    • 7.29.2.7 The timespec_getres function (p: TBD)

本文 更新于: 2025-11-27 09:38:11 创建于: 2025-11-27 09:38:11