1. time 函数
原型: time_t time(time_t *calptr)
得到自1970-1-1, 00:00:00以来经过的秒数,结果可以通过返回值,也可以通过参数得到,见实例
头文件 <time.h>
返回值:
成功:秒数
失败:-1
例:
time_t now;
time(&now);
// 等同于now = time(NULL)
printf("now time is %d\n", now);
2. localtime 用来获取系统时间,精度为秒
将时间(秒)数值变换成本地时间,考虑到本地时区和夏令时标志;
原型: struct tm *localtime(const time_t * calptr);
头文件 <time.h>
返回值:
成功: struct tm *结构体, 原型如下:
struct tm {
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值等于实际年份减去1900 */
int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一 */
int tm_yday; /* 从每年1月1日开始的天数– 取值区间[0,365],其中0代表1月1日 */
int tm_isdst; /* 夏令时标识符,夏令时tm_isdst为正;不实行夏令时tm_isdst为0 */
};
注意:此结构体空间由内核自动分配, 而且不要去释放它.
失败: NULL
例:
time_t now ;
struct tm *tm_now ;
time(&now) ;
tm_now = localtime(&now) ;//把秒变换成年月日
printf("now datetime: %d-%d-%d %d:%d:%d\n", tm_now->tm_year+1900, tm_now->tm_mon+1, tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec) ;
3. localtime_r 也是用来获取系统时间,运行于linux平台下
原型为struct tm *localtime_r(const time_t *timep, struct tm *result);
#include <stdio.h>
#include <time.h>
int main()
{
time_t time_seconds = time(0);
struct tm now_time;
localtime_r(&time_seconds, &now_time);
printf("%d-%d-%d %d:%d:%d\n", now_time.tm_year + 1900, now_time.tm_mon + 1,
now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
}
localtime、localtime_r 二者区别:
localtime对于多线程不安全,因为 localtime在使用时,只需定义一个指针,申请空间的动作由函数自己完成,这样在多线程的情况下,如果有另一个线程调用了这个函数,那么指针指向的struct tm结构体的数据就会改变。
在localtime_s与localtime_r调用时,定义的是struct tm的结构体,获取到的时间已经保存在struct tm中,并不会受其他线程的影响。
4. localtime_s 也是用来获取系统时间,运行于windows平台下,与localtime_r只有参数顺序不一样
#include <iostream>
#include <time.h>
int main()
{
time_t time_seconds = time(0);
struct tm now_time;
localtime_s(&now_time,&time_seconds);
printf("%d-%d-%d %d:%d:%d\n", now_time.tm_year + 1900, now_time.tm_mon + 1,
now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
}
5. gettimeofday 获取 秒,微妙,时区等信息.
#include <sys/time.h>
int gettimeofday(struct timeval*tv, struct timezone *tz); //其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果,timezone 参数若不使用则传入NULL即可。
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
例:
它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:
struct timeval tv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
gettimeofday(&tv_end, NULL);
函数执行成功后返回0,失败后返回-1,错误代码存于errno中