QT开发中文网

多核CPU的情况下,多线程编程,如何正确的使用QueryPerformanceCounter函数,每个要点写出相应的C代码例子

在多核CPU的情况下,使用QueryPerformanceCounter函数需要注意以下几个要点:

  1. 确保获取到的时间戳是在同一个核心上的,避免跨核心访问带来的性能影响。
  2. 使用互斥锁或原子操作等方式保证线程安全。
  3. 避免使用过于频繁的查询,以减少对性能的影响。

以下是相应的C代码例子:

要点1:确保在同一个核心上

#include <windows.h>
#include <stdint.h>

int64_t GetTimestamp() {
    LARGE_INTEGER timestamp, frequency;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&timestamp);
    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(&timestamp);
    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(&timestamp);
    if ((int64_t)timestamp.QuadPart - g_lastTimestamp <= frequency.QuadPart / 1000) {
        // 如果距离上次查询的时间间隔小于1ms,则等待一段时间再次查询
        Sleep(1);
        QueryPerformanceCounter(&timestamp);
    }
    g_lastTimestamp = (int64_t)timestamp.QuadPart;
    LeaveCriticalSection(&g_cs);

    return g_lastTimestamp * 1000000 / frequency.QuadPart;
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=399

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?