You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinAPI是否有函数可报告当前进程可用的处理器数量?

获取处理器亲和掩码中可用处理器数量的专用函数

在Windows平台下,确实存在专门的函数可以直接计算亲和掩码中二进制位为1的数量(即可用处理器的个数),无需手动统计:

  • __popcnt 系列内在函数:这是编译器提供的高效内在函数,针对x86/x64架构优化,能快速计算无符号整数中1的位数。32位掩码用__popcnt(unsigned int mask),64位掩码用__popcnt64(unsigned __int64 mask)。示例代码:

    #include <intrin.h>
    unsigned int affinityMask = 0b1011; // 示例掩码,对应3个可用处理器
    int coreCount = __popcnt(affinityMask);
    
  • BitCount 宏(Windows API):定义在winnt.h中,本质是对__popcnt的封装,可直接调用:

    #include <windows.h>
    DWORD affinityMask = 0b1011;
    int coreCount = BitCount(affinityMask);
    

如果需要兼容不支持POPCNT指令集的老旧处理器,也可以使用CountBits函数,不过现代系统中上述两种方式的效率更高。

内容的提问来源于stack exchange,提问作者Hovanella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:15:40