#C 语言标准库函数 timespec_get
/*********************************************
* @brief 根据时间基准获取当前时间
* @param ts 返回当前时间
* @param base 时间基准
* @return 是(0)否(非 0)成功
********************************************/
int timespec_get(struct timespec* ts, int base);
说明
根据时间基准获取当前时间。
时间基准 base
设为 TIME_UTC
时:
ts->tv_sec
被设为自某纪元(由实现定义)以来的秒数(截断为整数)ts->tv_nsec
被设为纳秒的整数(四舍五入到系统时间分辨率)
参数
ts
- 返回当前时间base
- 时间基准
返回值
- 成功时返回 0
- 失败时返回非 0
#示例
#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("当前时间为 %s.%09ld UTC\n", buff, ts.tv_nsec);
return 0;
}
运行结果:
当前时间为 10/12/25 02:03:03.176689984 UTC
#推荐阅读
#参考标准
- C23 standard (ISO/IEC 9899:2024):
- 7.29.2.6 The timespec_get function (p: TBD)
- C17 standard (ISO/IEC 9899:2018):
- 7.27.2.5 The timespec_get function (p: 286)
- C11 standard (ISO/IEC 9899:2011):
- 7.27.2.5 The timespec_get function (p: 390)