跨平台標準庫方法
方法一:手動組裝 time.h 結構體
time_t t = time(NULL);
struct tm* stime = localtime(&t);
char tmp[32];
sprintf(tmp, "%04d-%02d-%02d %02d:%02d:%02d",
1900+stime->tm_year, 1+stime->tm_mon, stime->tm_mday,
stime->tm_hour, stime->tm_min, stime->tm_sec);
// 輸出:2015-04-02 23:12:56
方法二:strftime 格式化(推薦)
time_t t = time(0);
char tmp[32];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&t));
// 輸出:2015-04-02 23:12:56
方法三:ctime/asctime 快速獲取
time_t tm; time(&tm);
char tmp[128]; strcpy(tmp, ctime(&tm));
// 輸出:Fri Aug 14 23:19:42 2015
Windows 平台專用:毫秒級精度
#include <windows.h>
SYSTEMTIME sys; GetLocalTime(&sys);
char tmp[64];
sprintf(tmp, "%4d-%02d-%02d %02d:%02d:%02d ms:%03d",
sys.wYear, sys.wMonth, sys.wDay,
sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds);
// 輸出:2015-08-14 23:41:56 ms:354
Unix/Linux 平台專用:gettimeofday 微秒級
#include <sys/time.h> #include <unistd.h>
struct timeval now; gettimeofday(&now, NULL);
time_t tt = now.tv_sec;
struct tm* temp = localtime(&tt);
char time_str[32];
sprintf(time_str, "%04d-%02d-%02d %02d:%02d:%02d",
temp->tm_year+1900, temp->tm_mon+1, temp->tm_mday,
temp->tm_hour, temp->tm_min, temp->tm_sec);
// 輸出:2015-08-14 23:41:56
核心知識點速查
| 概念 | 說明 |
| UTC | 協調世界時,原子鐘校準,中國為 UTC+8 |
| Calendar Time | 從 Epoch (1970-01-01 00:00:00 UTC) 到現在的秒數,time() 返回 |
| Epoch | Unix 時間戳起點 |
| clock tick | C/C++ 基本計時單位,CLOCKS_PER_SEC 通常為 1000,clock() 返回進程 CPU 時間 |
gmtime | 日歷時間 → UTC (tm 結構) |
localtime | 日歷時間 → 本地時間 (tm 結構) |
mktime | tm 結構 → 日歷時間,與上兩者互逆 |
測量程序運行時間範例
clock_t start = clock();
// ... 代碼段 ...
clock_t finish = clock();
long duration = (finish - start) / CLOCKS_PER_SEC; // 秒數