GetTickCount/timeGetTime 精度僅 ~10-15ms,無法測量微秒級代碼段。Windows 提供高精度計數器 QueryPerformanceCounter (QPC) + QueryPerformanceFrequency (QPF),基於 CPU 時鐘週期,精度可達納秒級。
CPrintfCodeTimeclass CPrintfCodeTime { public: explicit CPrintfCodeTime(const char* vCodeName) : m_strName(vCodeName ? vCodeName : "") { LARGE_INTEGER t; QueryPerformanceCounter(&t); m_llStart = t.QuadPart; } ~CPrintfCodeTime() { LARGE_INTEGER tEnd, freq; QueryPerformanceCounter(&tEnd); QueryPerformanceFrequency(&freq); double elapsedMs = double(tEnd.QuadPart - m_llStart) * 1000.0 / freq.QuadPart; char buf[128]; #ifndef __BORLANDC__ sprintf_s(buf, "運行時間: %.3f ms\n", elapsedMs); #else sprintf(buf, "運行時間: %.3f ms\n", elapsedMs); #endif OutputDebugStringA((m_strName + buf).c_str()); } private: std::string m_strName; long long m_llStart; };
void heavyFunction() { CPrintfCodeTime timer("heavyFunction: "); // 構造即開始計時 // ... 耗時操作 ... } // 析構自動打印耗時到調試輸出
LARGE_INTEGER.QuadPart 為 64 位計數值,防溢出。freq 通常恆定,可靜態緩存避免重複查詢。OutputDebugStringA 輸出到調試器(Visual Studio 輸出窗口、DbgView 等),不干擾標準輸出。clock_gettime(CLOCK_MONOTONIC, ...),C++20 用 std::chrono::high_resolution_clock。SetThreadAffinityMask。sprintf_s 為 MSVC 安全版本,跨平台代碼用 snprintf。