如何获取windows系统资源

来源:互联网 发布:姐妹团推广 网络诈骗 编辑:程序博客网 时间:2024/05/29 23:45
  • 总的虚拟内存:

 


    #include "windows.h" 
    
    MEMORYSTATUSEX memInfo; 
    memInfo.dwLength = sizeof(MEMORYSTATUSEX); 
    GlobalMemoryStatusEx(&memInfo); 
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;

注:名称“TotalPageFile”是有些误导这里。 在现实中这个参数给“虚拟内存大小”,这是交换文件,另加安装的RAM的大小。

 

  • 目前使用的虚拟内存:

相同的代码,如“总的虚拟内存”,然后


    DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;

 

 

  • 目前使用的虚拟内存的当前进程:

 


    #include "windows.h" 
    #include "psapi.h" 
    
    PROCESS_MEMORY_COUNTERS_EX pmc; 
    GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); 
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;

 

 

  • 总物理内存(RAM):

相同的代码,如“总的虚拟内存”,然后


    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;

 

 

  • 目前使用的物理内存:

相同的代码,如“总的虚拟内存”,然后


    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;

 

 

  • 目前使用的物理内存的当前进程:

在“虚拟内存相同的代码目前使用的当前进程”,然后


    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;

 

 

  • 目前使用的CPU:

 


    #include "TCHAR.h" 
    #include "pdh.h" 
    
    static PDH_HQUERY cpuQuery; 
    static PDH_HCOUNTER cpuTotal; 
    
    void init(){ 
    PdhOpenQuery(NULL, NULL, &cpuQuery); 
    PdhAddCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal); 
    PdhCollectQueryData(cpuQuery); 
    } 
    
    double getCurrentValue(){ 
    PDH_FMT_COUNTERVALUE counterVal; 
    
    PdhCollectQueryData(cpuQuery); 
    PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal); 
    return counterVal.doubleValue; 
    }

 

 

  • 目前使用的CPU的当前进程:

 


    #include "windows.h" 
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; 
    static int numProcessors; 
    static HANDLE self; 
    
    void init(){ 
    SYSTEM_INFO sysInfo; 
    FILETIME ftime, fsys, fuser; 
    
    GetSystemInfo(&sysInfo); 
    numProcessors = sysInfo.dwNumberOfProcessors; 
    
    GetSystemTimeAsFileTime(&ftime); 
    memcpy(&lastCPU, &ftime, sizeof(FILETIME)); 
    
    self = GetCurrentProcess(); 
    GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); 
    memcpy(&lastSysCPU, &fsys, sizeof(FILETIME)); 
    memcpy(&lastUserCPU, &fuser, sizeof(FILETIME)); 
    } 
    
    double getCurrentValue(){ 
    FILETIME ftime, fsys, fuser; 
    ULARGE_INTEGER now, sys, user; 
    double percent; 
    
    GetSystemTimeAsFileTime(&ftime); 
    memcpy(&now, &ftime, sizeof(FILETIME)); 
    
    GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); 
    memcpy(&sys, &fsys, sizeof(FILETIME)); 
    memcpy(&user, &fuser, sizeof(FILETIME)); 
    percent = (sys.QuadPart - lastSysCPU.QuadPart) + 
    (user.QuadPart - lastUserCPU.QuadPart); 
    percent /= (now.QuadPart - lastCPU.QuadPart); 
    percent /= numProcessors; 
    lastCPU = now; 
    lastUserCPU = user; 
    lastSysCPU = sys; 
    
    return percent * 100; 
    }

0 0