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

相關文章
相關標籤/搜索