Namespaces
Variants

timespec_get

From cppreference.net
定义于头文件 <time.h>
int timespec_get ( struct timespec * ts, int base ) ;
(1) (C11 起)
#define TIME_UTC /* 由实现定义 */
(2) (C11 起)
1) 修改由 ts 指向的 timespec 对象,使其保存时间基准 base 中的当前日历时间。
2) 扩展为适合用作 timespec_get 函数的 base 参数的数值

其他以 TIME_ 开头的宏常量可由实现提供,用于指示额外的时间基准

如果 base TIME_UTC ,那么

  • ts - > tv_sec 被设置为自实现定义纪元以来的秒数,截断为整数值
  • ts - > tv_nsec 成员被设置为纳秒的整数值,舍入到系统时钟的分辨率

目录

参数

ts - 指向 struct timespec 类型对象的指针
base - TIME_UTC 或表示时间基准的其他非零整数值

返回值

成功时的值为 base ,否则为零。

注释

POSIX函数 clock_gettime(CLOCK_REALTIME, ts) 也可用于将自纪元起的时间填充至 timespec 结构体。

示例

#include <stdio.h>
#include <time.h>
int main(void)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
}

可能的输出:

Current time: 02/18/15 14:34:03.048508855 UTC

参考文献

  • C23 标准 (ISO/IEC 9899:2024):
  • 7.27.2.5 timespec_get 函数 (页: TBD)
  • C17 标准 (ISO/IEC 9899:2018):
  • 7.27.2.5 timespec_get 函数 (p: 286)
  • C11 标准 (ISO/IEC 9899:2011):
  • 7.27.2.5 timespec_get 函数 (p: 390)

参见

以秒和纳秒表示的时间
(结构体)
基于给定时间基准返回日历时间的精度
(函数)
返回系统当前日历时间(自纪元起的时间)
(函数)
C++ 文档 for timespec_get