C語言的時間函數
-------- 頭文件
time.h
-------- 相關函數和接口
asctime() 將時間日期以字符串格式表示
ctime() 將時間日期以字符串格式表示
gettimeofday() 獲取當前時間
gmtime() 獲取當前時間和日期
localtime() 獲取當前時間和日期並轉換為本地時間
mktime() 將時間轉換成經過的秒數
settimeofday() 設置當前時間戳
time() 獲取當前時間(以秒數表示)
struct tm*gmtime(const time_t*timep);
int gettimeofday ( struct timeval * tv , struct timezone * tz )
char *ctime(const time_t *timep);
struct tm *localtime(const time_t * timep);
time_t mktime(strcut tm * timeptr);
int settimeofday ( const struct timeval *tv,const struct timezone *tz);
time_t 是一個長整型數
tm 結構體類型
timeval 包含秒和微秒的結構體
-------- 例子
#include <time.h> main() { time_t timep; time (&timep); printf("%s",asctime(gmtime(&timep))); }
C++ 語言的時間函數
標准庫沒有提供所謂的日期類型。C++ 繼承了 C 語言用於日期和時間操作的結構和函數。
Windows 平台的時間函數
-------- 頭文件
<windows.h>
-------- 相關函數和接口
GetSystemTime 獲得UTC(等於GMT)時間
GetLocalTime 獲得系統本地時間
-------- 例子
#include <windows.h> #include <stdio.h> void main() { SYSTEMTIME st, lt; GetSystemTime(&st); GetLocalTime(<); printf("The system time is: %02d:%02d\n", st.wHour, st.wMinute); printf("The local time is: %02d:%02d\n", lt.wHour, lt.wMinute); }
Linux 平台的時間函數
-------- 頭文件
<sys/time.h>
-------- 相關函數和接口
int gettimeofday(struct timeval *restrict tp, void *restrict tzp);
-------- 例子
#include <stdio.h> #include <sys/time.h> int main() { struct timeval start, end; gettimeofday( &start, NULL ); sleep(3); gettimeofday( &end, NULL ); //求出兩次時間的差值,單位為us int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; printf("time: %d us\n", timeuse); return 0; }