time()函數:
NAME
time - get time in seconds
SYNOPSIS
#include <time.h>
time_t time(time_t *tloc);
/* typedef long time_t; */
DESCRIPTION
time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc.
返回從公元1970-01-01的UTC時間 從00:00:00 到現在所經歷的描述,如果tloc非空,返回值也會存儲到tloc指向的內存
RETURN VALUE
On success, the value of time in seconds since the Epoch is returned. On error, ((time_t) -1) is returned, and errno is set appropriately.
執行成功,返回秒數
執行失敗,返回-1
localtime()函數
作用:
localtime是 把從1970-1-1零點零分到當前時間系統所偏移的秒數時間轉換為本地時間
原型:
struct tm *localtime(const time_t *timer)
- const time_t *time:這是指向表示日歷時間的 time_t 值的指針,由time()函數返回
返回值:
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 到 11 */
int tm_year; /* 自 1900 起的年數 */
int tm_wday; /* 一周中的第幾天,范圍從 0 到 6 */
int tm_yday; /* 一年中的第幾天,范圍從 0 到 365 */
int tm_isdst; /* 夏令時 */ };
例子:
#include <stdio.h> #include <time.h> int main () { time_t rawtime; struct tm *info; char buffer[80]; time( &rawtime ); info = localtime( &rawtime ); printf("當前的本地時間和日期:%s", asctime(info)); return(0); }
asctime()函數
原型:
char* asctime (const struct tm * timeptr)
作用:
把timeptr指向的tm結構體中儲存的時間轉換為字符串,返回的字符串格式為:Www Mmm dd hh:mm:ss yyyy。其中Www為星期;Mmm為月份;dd為日;hh為時;mm為分;ss為秒;yyyy為年份。
參數:
- const struct tm * timept:由localtime()函數返回
返回值:
時間字符串
例子:
/* asctime example */ #include <stdio.h> /* printf */ #include <time.h> /* time_t, struct tm, time, localtime, asctime */ int main () { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); printf ( "The current date/time is: %s", asctime (timeinfo) ); return 0; }
The current date/time is: Wed Feb 13 15:46:46 2018
gettimeofday()函數
原型:
作用:
獲得當前精確時間(1970年1月1日到現在的時間),或者為執行計時,可以使用gettimeofday()函數。
參數:
- struct timeval*tv
struct timeval{long int tv_sec; // 秒數long int tv_usec; // 微秒數} - struct timezone *tz
struct timezone{int tz_minuteswest; /*格林威治時間往西方的時差*/int tz_dsttime;/*DST 時間的修正方式*/}
返回值:
執行成功,返回0
執行失敗,返回-1
例子:
它獲得的時間精確到微秒(1e-6 s)量級。在一段代碼前后分別使用gettimeofday可以計算代碼執行時間:
struct timeval tv_begin, tv_end; gettimeofday(&tv_begin, NULL); foo(); gettimeofday(&tv_end, NULL);
