Linux系统下C语言获取Time

获取时间的函数有不少,具体包括以下:ios

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]\n",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;
}

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

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

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

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

/* 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。blog

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

struct tm结构的成员以下:io

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

未完待续!ast

相关文章
相关标签/搜索