| 函數 | 精度 | 說明 |
|---|---|---|
time() | 秒 | 從 1970-01-01 秒數,time_t 通常為長整型 |
clock() | ~微秒 | CPU 時間,非牆鐘時間,精度 CLOCKS_PER_SEC |
difftime() | 秒 | 兩 time_t 差值,回傳 double |
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv, NULL); // 秒 tv_sec + 微秒 tv_usec
// 精度 ~1 微秒,但系統調用開銷較大
// 更現代:clock_gettime (POSIX.1-2001)
#include <time.h>
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts); // 奈秒級牆鐘時間
clock_gettime(CLOCK_MONOTONIC, &ts); // 單調時鐘,不受系統時間調整影響,適合計時
// 毫秒級
DWORD GetTickCount(); // 系統啟動後毫秒,49.7 天溢位
DWORD GetTickCount64(); // 64 位,不溢位
// 高精度效能計數器
LARGE_INTEGER freq, start, end;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
// ... 代碼 ...
QueryPerformanceCounter(&end);
double elapsed_ms = (end.QuadPart - start.QuadPart) * 1000.0 / freq.QuadPart;
// 多媒體計時器 (較舊)
timeBeginPeriod(1); // 設定 1ms 精度
DWORD t = timeGetTime(); // 約 1ms 精度
timeEndPeriod(1);
CTime t = CTime::GetCurrentTime(); // 秒級
CTimeSpan span = t - t0; // 時間差
SYSTEMTIME st;
GetLocalTime(&st); // 含毫秒 wMilliseconds
time_t raw = time(NULL);
struct tm *info = localtime(&raw);
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", info);
printf("%s\n", buf);
time() + localtime/gmtime + strftime。clock_gettime(CLOCK_MONOTONIC) 或 QueryPerformanceCounter。GetTickCount64 (Win) / clock_gettime (Linux)。clock() 測量牆鐘時間 → 錯誤,它測 CPU 時間,多執行緒會加總。GetTickCount 溢位 → 長時間運行程式必須用 GetTickCount64。time_t 32 位系統 2038 年溢位 → 用 64 位 time_t 或 int64_t。time_t 計算差值 → 應用 difftime 避免無號溢位。理解各時間 API 的語義(牆鐘 vs CPU、單調 vs 可調)、精度與平台差異,是編寫正確計時、日誌、排程代碼的前提。