time()函数与time_t类型
头文件:time.h
函数签名:time_t time( time_t *arg )
说明:返回当前计算机纪元时间,并将其存储在arg指向的time_t类型中。所以可以time_t result = time(NULL)
,也可以time(&result)
。
计算机纪元时间:C语言和Unix创造并诞生于1970年,所以计算机以1970年1月1日作为纪元开始时间。
C语言标准并没有指定time_t类型的编码方式,但大多数遵循POSIX标准系统的time_t一般是32位有符号整数实现,以秒为最小单位,从1970年1月1日开始计数,所以能表示到2038年。
VS2017中有如下定义:
#ifndef _CRT_NO_TIME_T
#ifdef _USE_32BIT_TIME_T
typedef __time32_t time_t;
#else
typedef __time64_t time_t;
#endif
#endif
...
#ifdef _USE_32BIT_TIME_T
...
static __inline time_t __CRTDECL time(
_Out_opt_ time_t* const _Time
)
{
return _time32(_Time);
}
...
#else
...
static __inline time_t __CRTDECL time(
_Out_opt_ time_t* const _Time
)
{
return _time64(_Time);
}
...
#endif
因为time_t类型编码不能确定,所以尽量不要用t1-t2
方式计算两个time_t
之间的时间间隔,而应该用double difftime( time_t time_end, time_t time_beg );
函数计算时间间隔。
扩展:time_t
表示计算机纪元时间,struct tm
表示标准日历时间。
struct tm
定义如下:
struct tm
{
int tm_sec; // seconds after the minute - [0, 60] including leap second
int tm_min; // minutes after the hour - [0, 59]
int tm_hour; // hours since midnight - [0, 23]
int tm_mday; // day of the month - [1, 31]
int tm_mon; // months since January - [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday - [0, 6]
int tm_yday; // days since January 1 - [0, 365]
int tm_isdst; // daylight savings time flag
};
time_t
可以和struct tm
格式的时间进行互相转换:
struct tm *gmtime( const time_t *time )
:从time_t
转成struct tm
,但该函数C11标准中才定义的。time_t mktime( struct tm *time )
:从struct tm
转成time_t
。
示例:
time_t start, end;
start = time(NULL);
_sleep(1000);
end = time(NU