在多核CPU的情况下,使用QueryPerformanceCounter函数需要注意以下几个要点:
- 确保获取到的时间戳是在同一个核心上的,避免跨核心访问带来的性能影响。
- 使用互斥锁或原子操作等方式保证线程安全。
- 避免使用过于频繁的查询,以减少对性能的影响。
以下是相应的C代码例子:
要点1:确保在同一个核心上
#include <windows.h>
#include <stdint.h>
int64_t GetTimestamp() {
LARGE_INTEGER timestamp, frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(×tamp);
return (int64_t)timestamp.QuadPart * 1000000 / frequency.QuadPart;
}
要点2:保证线程安全
#include <windows.h>
#include <stdint.h>
CRITICAL_SECTION g_cs = {0};
int64_t GetTimestamp() {
LARGE_INTEGER timestamp, frequency;
QueryPerformanceFrequency(&frequency);
EnterCriticalSection(&g_cs);
QueryPerformanceCounter(×tamp);
LeaveCriticalSection(&g_cs);
return (int64_t)timestamp.QuadPart * 1000000 / frequency.QuadPart;
}
要点3:避免过于频繁的查询
#include <windows.h>
#include <stdint.h>
CRITICAL_SECTION g_cs = {0};
int64_t g_lastTimestamp = 0;
int64_t GetTimestamp() {
LARGE_INTEGER timestamp, frequency;
QueryPerformanceFrequency(&frequency);
EnterCriticalSection(&g_cs);
QueryPerformanceCounter(×tamp);
if ((int64_t)timestamp.QuadPart - g_lastTimestamp <= frequency.QuadPart / 1000) {
// 如果距离上次查询的时间间隔小于1ms,则等待一段时间再次查询
Sleep(1);
QueryPerformanceCounter(×tamp);
}
g_lastTimestamp = (int64_t)timestamp.QuadPart;
LeaveCriticalSection(&g_cs);
return g_lastTimestamp * 1000000 / frequency.QuadPart;
}