zoukankan      html  css  js  c++  java
  • Linux系统下C语言获取Time

    获取时间的函数有很多,具体包括如下:

    time()/gettimeofday()等等,下面是获取具体到usecond的时间程序:

    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/time.h>
    
    using namespace std;
    
    int main() {
        struct tm *tm;
        struct timeval tv;
    
        gettimeofday(&tv,NULL);
        tm = localtime(&tv.tv_sec);
    
        printf("[%d-%02d-%02d %02d:%02d:%02d:%02d]
    ",tm->tm_year + 1900,tm->tm_mon + 1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec);
    
        return 0;
    }

    程序中需要引入对应的头文件:

    #include <time.h>
    #include <sys/time.h>

    程序中调用了gettimeofday函数,函数获得的结果保存在结构体tv中。

    struct timeval结构体的成员如下所示:

    /* A time value that is accurate to the nearest
       microsecond but also has a range of years.  */
    struct timeval
      {
        __time_t tv_sec;        /* Seconds.  */
        __suseconds_t tv_usec;    /* Microseconds.  */
      };

    包括了两个部分,第一部分是second秒,第二部分是毫秒usecond。

    localtime函数的作用是将秒second转换为year、month、day、hour、minute、second。并把转换的结果保存在tm结构体中。

    struct tm结构的成员如下:

    /* Used by other time functions.  */
    struct tm
    {
      int tm_sec;            /* Seconds.    [0-60] (1 leap second) */
      int tm_min;            /* Minutes.    [0-59] */
      int tm_hour;            /* Hours.    [0-23] */
      int tm_mday;            /* Day.        [1-31] */
      int tm_mon;            /* Month.    [0-11] */
      int tm_year;            /* Year    - 1900.  */
      int tm_wday;            /* Day of week.    [0-6] */
      int tm_yday;            /* Days in year.[0-365]    */
      int tm_isdst;            /* DST.        [-1/0/1]*/
    
    # ifdef    __USE_MISC
      long int tm_gmtoff;        /* Seconds east of UTC.  */
      const char *tm_zone;        /* Timezone abbreviation.  */
    # else
      long int __tm_gmtoff;        /* Seconds east of UTC.  */
      const char *__tm_zone;    /* Timezone abbreviation.  */
    # endif
    };

    未完待续!

  • 相关阅读:
    Vue的配置安装与项目创建
    log4j:WARN No appenders could be found for logger
    终于在博客园扎根了
    简单工厂模式
    详解apache防盗链网站图片防盗链方法
    怎样能写好文章标题
    生活需要阿Q精神
    2013个人博客全新起航
    华中师范大学新生网上怎么选宿舍
    华中师范大学2012级新生QQ交流群欢迎加入!
  • 原文地址:https://www.cnblogs.com/uestc-mm/p/10906579.html
Copyright © 2011-2022 走看看