zoukankan      html  css  js  c++  java
  • 时间获取函数

    由Linux内核提供的基本时间是自1970-01-01 00:00:00 +0000 (UTC)这一特定时间以来经过的秒数,这种描述是以数据类型time_t表示的,我们称其为日历时间。
    获得日历时间的函数有3个:time、clock_gettime和gettimeofday。

    time函数

    #include <time.h>
    
    //成功返回日历时间,出错返回-1;若time非NULL,则也通过其返回时间值
    time_t time(time_t *time);
    
    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    
    void print_time()
    {
        time_t seconds = time(NULL);
    
        printf("seconds = %ld
    ", seconds);
    }
    
    int main()
    {
        print_time();
    
        return 0;
    }
    

    clock_gettime函数

    clock_gettime函数可用于获取指定时钟的时间,返回的时间通过struct timespec结构保存,该结构把时间表示为秒和纳秒。

    #include <time.h>
    
    struct timespec
    {
        time_t   tv_sec;        /* seconds */
        long     tv_nsec;       /* nanoseconds */
    };
    
    //Link with -lrt.
    int clock_gettime(clockid_t clock_id, struct timespec *tsp);
    

    clock_id一般设置为CLOCK_REALTIME以获取高精度日历时间。

    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    
    void print_time()
    {
        time_t seconds;
        struct timespec tsp;
    
        seconds = time(NULL);
        printf("seconds = %ld
    ", seconds);
    
        clock_gettime(CLOCK_REALTIME, &tsp);
        printf("tsp.tv_sec = %ld, tsp.tv_nsec = %ld
    ", tsp.tv_sec, tsp.tv_nsec);
    }
    
    int main()
    {
        print_time();
    
        return 0;
    }
    

    gettimeofday函数

    和clock_gettime函数类似,gettimeofday通过struct timeval结构返回日历时间,该结构把时间表示为秒和微妙。

    #include <sys/time.h>
    
    struct timeval
    {
        time_t      tv_sec;     /* seconds */
        suseconds_t tv_usec;    /* microseconds */
    };
    
    int gettimeofday(struct timeval *tv, struct timezone *tz);
    

    需要注意的是,参数tz的唯一合法值是NULL。

    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    #include <sys/time.h>
    
    void print_time()
    {
        time_t seconds;
        struct timespec tsp;
        struct timeval tv;
    
        seconds = time(NULL);
        printf("seconds = %ld
    ", seconds);
    
        clock_gettime(CLOCK_REALTIME, &tsp);
        printf("tsp.tv_sec = %ld, tsp.tv_nsec = %ld
    ", tsp.tv_sec, tsp.tv_nsec);
    
        gettimeofday(&tv, NULL);
        printf("tv.tv_sec = %ld, tv.tv_usec = %ld
    ", tv.tv_sec, tv.tv_usec);
    }
    
    int main()
    {
        print_time();
    
        return 0;
    }
    

  • 相关阅读:
    kolla多节点部署openstack
    归并排序
    gitlab ci/cd
    微信、支付宝个人收款码不能用于经营收款 z
    微信小程序弹出和隐藏遮罩层动画以及五星评分
    centos7 安装 nginx
    netty+websocket模式下token身份验证遇到的问题
    windows 截图 win+shift+s
    linux下 "chmod 777" 中777这个数字是怎么出来的
    nginx四层转发,访问内网mysql数据库
  • 原文地址:https://www.cnblogs.com/songhe364826110/p/11546104.html
Copyright © 2011-2022 走看看