名稱空間
變體
操作

timespec

來自 cppreference.com
< c‎ | 時間
定義於標頭檔案 <time.h>
struct timespec;
(C11 起)

將時間間隔分解為秒和納秒的結構體。

目錄

[編輯] 成員物件

成員 描述
time_t tv_sec 整數秒(有效值 >= 0
/* 見下文 */ tv_nsec 納秒(有效值 [0999999999]

tv_nsec 的型別是 long

(直至 C23)

tv_nsec 的型別是實現定義的有符號整數型別,可表示 [0999999999] 範圍內的整數。

(自 C23 起)

tv_sectv_nsec 的宣告順序未指定。實現可以向 struct timespec 新增其他成員。

[編輯] 注意

在某些平臺上,tv_nsec 的型別是 long long,這僅在 C23 及之後才符合標準。

[編輯] 示例

#include <stdint.h>
#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);
    printf("Raw timespec.tv_sec: %jd\n", (intmax_t)ts.tv_sec);
    printf("Raw timespec.tv_nsec: %09ld\n", ts.tv_nsec);
}

可能的輸出

Current time: 04/04/24 14:45:17.885909786 UTC
Raw timespec.tv_sec: 1712241917
Raw timespec.tv_nsec: 885909786

[編輯] 參考

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.27.1/3 時間元件 (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.27.1/3 時間元件 (p: 284)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.27.1/3 時間元件 (p: 388)

[編輯] 另見

根據給定時間基準返回以秒和納秒錶示的日曆時間
(函式) [編輯]
日曆時間型別
(結構體)[編輯]
C++ 文件 關於 timespec