当前位置: C语言 -- 标准库 -- <time.h> -- TIME_MONOTONIC

TIME_MONOTONIC宏


概要:
#include <time.h>
#define TIME_MONOTONIC value  //value值由具体实现定义。

描述:

该宏为可选宏,会扩展为大于0的整数常量,用于指定单调时间基准(monotonic time base)。

实现可能会定义以TIME_和一个大写字母开头的其它时间基准宏;但ISO/IEC 9899标准要求:实现必须支持TIME_UTC时间基准,TIME_UTC以外的其它时间基准是可选的。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
/*宏TIME_MONOTONIC范例*/

#include <stdio.h>
#include <stdlib.h>
#include <threads.h>  //<threads.h>头文件包含<time.h>。

int main(void)
{
    #ifdef TIME_MONOTONIC
        struct timespec startTime;
        struct timespec endTime;
        struct timespec sleepTime = {5, 0};
        double period;
        
        /*获取开始时间。*/
        if(timespec_get(&startTime,TIME_MONOTONIC) == 0)
        {
            fprintf(stderr, "timespec_get function failed.\n");
            exit(EXIT_FAILURE);
        }
        
        /*模拟工作。*/
        thrd_sleep(&sleepTime, NULL);
        
        /*获取结束时间。*/
        if(timespec_get(&endTime,TIME_MONOTONIC) == 0)
        {
            fprintf(stderr, "timespec_get function failed.\n");
            exit(EXIT_FAILURE);
        }
        
        /*输出耗时。*/
        period = (double)(endTime.tv_sec - startTime.tv_sec)
                + (double)(endTime.tv_nsec - startTime.tv_nsec)/1E9;
        
        printf("period: %.9f seconds.\n", period);
    #else
        puts("The implementation does not define macro TIME_MONOTONIC.");
    #endif

    return 0;
}


输出:

The implementation does not define macro TIME_MONOTONIC.

(注:编译时实现还未支持宏TIME_MONOTONIC。)


相关内容:
struct timespec 表示时间的结构类型。
timespec_get 设置并保存基于指定时间基准日历时间的函数。
TIME_UTC 表示以UTC时间为基准的整型常量的宏。
TIME_ACTIVE 表示以总执行时间为基准的整型常量的宏。
TIME_THREAD_ACTIVE 表示以线程特定活动处理时间为基准的整型常量的宏。


主要参考资料:

1、ISO/IEC 9899:2024