Unix时间处理函数全解析
1. 获取当前时间
1.1 time()函数
time()函数用于返回自纪元(epoch)以来经过的秒数来表示当前时间。如果参数t不为NULL,该函数还会将当前时间写入提供的指针。
#include <time.h> time_t t; printf ("current time: %ld\n", (long) time (&t)); printf ("the same value: %ld\n", (long) t);若出现错误,函数返回-1(转换为time_t类型)并设置errno。唯一可能的错误是EFAULT,表示t是无效指针。
1.2 gettimeofday()函数
gettimeofday()函数通过提供微秒级分辨率扩展了time()函数。
#include <sys/time.h> int gettimeofday (struct timeval *tv, struct timezone *tz);