获取时间的函数有很多,具体包括如下:
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 };
未完待续!