命名空间
变体
操作

std::timespec

来自 cppreference.cn
< cpp‎ | chrono‎ | c
 
 
 
 
定义于头文件 <ctime>
struct timespec;
(自 C++17 起)

结构体,用于保存分解为秒和纳秒的时间间隔。

内容

[编辑] 数据成员

成员 描述
完整秒数,值 >= 0
(公共成员对象)
long tv_nsec
纳秒,值在范围 [0999999999]
(公共成员对象)

tv_sectv_nsec 的声明顺序未指定。实现可能向 timespec 添加其他数据成员。

[编辑] 注解

tv_nsec 的类型在某些平台上是 long long,这在 C++ 中目前是不符合标准的,但在 C 中自 C23 起是允许的。

[编辑] 示例

#include <ctime>
#include <iostream>
 
int main()
{
    std::timespec ts;
    std::timespec_get(&ts, TIME_UTC);
    char buff[0x80];
    std::strftime(buff, sizeof buff, "%D %T", std::gmtime(&ts.tv_sec));
 
//  auto [sec, nsec] = ts; // UB: structured bindings should not be used because the
                           // declaration order and data member list are unspecified
 
    std::cout << "Current time: " << buff << " (UTC)\n"
              << "Raw timespec.tv_sec: " << ts.tv_sec << '\n'
              << "Raw timespec.tv_nsec: " << ts.tv_nsec << '\n';
}

可能的输出

Current time: 04/06/23 12:03:31 (UTC)
Raw timespec.tv_sec: 1680782611
Raw timespec.tv_nsec: 678437213

[编辑] 参见

基于给定的时间基准返回秒和纳秒的日历时间
(函数) [编辑]
日历时间类型
(类) [编辑]
C 文档 关于 timespec