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;
    }
    

  • 相关阅读:
    30+简约时尚的Macbook贴花
    20+非常棒的Photoshop卡通设计教程
    20+WordPress手机主题和插件【好收藏推荐】
    75+精美的网格网站设计欣赏
    TopFreeTheme精选免费模板【20130629】
    45个有新意的Photoshop教程和技巧
    30个高质量的旅游网站设计
    55个高质量的Magento主题,助你构建电子商务站点
    一个弹框引起的彻夜加班
    开始跟踪Redis啦,开帖
  • 原文地址:https://www.cnblogs.com/songhe364826110/p/11546104.html
Copyright © 2011-2022 走看看