获取系统的CPU个数的vc代码

在做代码优化的时候,有时需要读取系统的CPU个数,来制定不同的多线程优化策略。在vc程序中如何获取系统的CPU个数呢?

如何获取系统的CPU个数的vc代码如下(调用ntdll.dll中的NtQuerySystemInformation函数):


#include <windows.h>

//一些预定义---
#define SystemBasicInformation 0
#define SystemPerformanceInformation 2
#define SystemTimeInformation 3
#define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))

//存储系统基本信息的结构体
typedef struct
{
    DWORD dwUnknown1;
    ULONG uKeMaximumIncrement;
    ULONG uPageSize;
    ULONG uMmNumberOfPhysicalPages;
    ULONG uMmLowestPhysicalPage;
    ULONG uMmHighestPhysicalPage;
    ULONG uAllocationGranularity;
    PVOID pLowestUserAddress;
    PVOID pMmHighestUserAddress;
    ULONG uKeActiveProcessors;
    BYTE bKeNumberProcessors;
    BYTE bUnknown2;
    WORD wUnknown3;
} SYSTEM_BASIC_INFORMATION;

//声明一个函数指针类型
typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);

PROCNTQSI NtQuerySystemInformation;

int GetCpuNum()
{
    SYSTEM_BASIC_INFORMATION SysBaseInfo;
    LONG status;

    //获得ntdll.dll中NtQuerySystemInformation函数指针
    NtQuerySystemInformation=(PROCNTQSI)GetProcAddress(
        GetModuleHandleA("ntdll") , "NtQuerySystemInformation");
    if (!NtQuerySystemInformation)
        return 1;
    
    //获取系统基本信息,这里要得到系统的CPU个数
    status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
    if (status != NO_ERROR)
        return 1;

    return SysBaseInfo.bKeNumberProcessors;
}



文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: CPU 代码
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.