C 语言获取日历时间一般用time()函数,该函数返回类型为time_t,即一个无符号整型时间戳,该值表示从时间原点(00:00:00 on January 1, 1970)到此刻所经历的秒数。然后可以将time_t类型的时间转为一个结构体tm,从而获得年月日等值。
struct tm { int tm_sec; /* seconds */ int tm_min; /* minutes */ int tm_hour; /* hours */ int tm_mday; /* day of the month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of the week */ int tm_yday; /* day in the year */ int tm_isdst; /* daylight saving time */ };
转换函数有如下几种 struct tm *gmtime(const time_t *timep); struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime(const time_t *timep); struct tm *localtime_r(const time_t *timep, struct tm *result);
例如典型的转换如下方式:
tm starttm; time_t timer; timer = time(NULL); localtime_r(&timer,&starttm); printf("time() -> %02d%02d%02d %2d:%02d:%02d \n",starttm.tm_year%100,starttm.tm_mon+1,starttm.tm_mday,starttm.tm_hour,starttm.tm_min,starttm.tm_sec);
使用time()函数只能获得秒级别的时间精度。如果需要更精确的时间,则可以用ftime()函数,gettimeofday(),clock_gettime()函数。ftime()函数可以精确到毫秒级,gettimeofday精确到毫秒级,clock_gettime可以精确到纳秒。由于POSIX标准中ftime函数已不推荐使用。一般使用较多的是gettimeofday函数。纳秒级别的精度目前用途不广而且支持的系统有限。
gettimeofday()函数 在sys/time.h头文件中定义,与之配套的还有一个settimeofday()函数,用于设置系统时间。其函数原型如下
int gettimeofday(struct timeval *tv, struct timezone *tz); int settimeofday(const struct timeval *tv , const struct timezone *tz);
使用gettimeofday()涉及到timeval结构体和timezone,其中timeval结构体用以记录一个秒级时间以及一个微秒级时间,timeval记录的也是相对时间原点的差值,也需要通过local_time系列的函数进行转换以获取时间戳。
struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ };
不关注timezone时,可以向gettimeofday传入一个NULL参数。
一般通过如下方式来获取当前日历时间
struct timeval start; struct tm starttm; gettimeofday(&start,NULL); //getimeofday() localtime_r(&(start.tv_sec),&starttm); printf("gettimeofday() ->%02d%02d%02d %2d:%02d:%02d:%03lu \n",starttm.tm_year%100,starttm.tm_mon+1,starttm.tm_mday,starttm.tm_hour,starttm.tm_min,starttm.tm_sec,start.tv_usec);
或者通过如下方式获得一个微妙级别的时间间隔
struct timeval start,end; gettimeofday(&start,NULL); gettimeofday(&end,NULL); printf("%lu us\n",(end.tm_sec-start.tm_sec)*10000000+end.tv_usec-start.tv_usec);
|