vc中获取电脑CPU占有率和内存占有率的API

32 篇文章 1 订阅
26 篇文章 2 订阅

使用下列函数可以得到系统进程列表,具体分析可得其PID等信息。。

class Process
{
public:
static const uint32 INVALID_ID = (uint32)-1;


uint32 m_nId;
uint32 m_nParentId;
std::string m_strBinPath;
std::string m_strCommandLine;
std::string m_strWorkPath;
std::string m_strName;
std::string m_strDescribe;
bool m_bIsSystem;
HICON m_hIcon;


bool m_bZombie;
uint32 m_nThreadCount;
uint64 m_nVirtualMemorySize;
uint64 m_nPhysicalMemorySize;
uint64 m_nUserTime;
uint64 m_nKernelTime;
uint64 m_nCreationTime;


//added by liufia 2013-12-24
uint64 m_nCpuUsage;
uint64 m_nMemUsage;
uint64 m_nIdleTime;


Process()
{
m_nId       = 0;
m_nParentId = 0;
m_bZombie   = false;
m_nThreadCount = 0;
m_nVirtualMemorySize  = 0;
m_nPhysicalMemorySize = 0;
m_nIdleTime = 0;
};
};


、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

char szPath[Utils::File::MAX_PATH_LEN] = {0};
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if( INVALID_HANDLE_VALUE == hSnapShot )
{
return false;
}


PROCESSENTRY32 nProcessEntry = {0};
nProcessEntry.dwSize = sizeof(nProcessEntry);


if( !Process32First(hSnapShot, &nProcessEntry) )
{
CloseHandle(hSnapShot);
return false;
}


nArray.clear();

TCHAR nCharTmp[1024] = {0};
do
{
Process nNewProcess;
nNewProcess.m_nId = (uint32)nProcessEntry.th32ProcessID;
nNewProcess.m_nParentId = (uint32)nProcessEntry.th32ParentProcessID;
nNewProcess.m_nThreadCount = (uint32)nProcessEntry.cntThreads;
memset(nCharTmp,0,sizeof(nCharTmp));
strcpy_s(nCharTmp,sizeof(nProcessEntry.szExeFile), nProcessEntry.szExeFile);
nNewProcess.m_strName = std::string(nCharTmp);


HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, nProcessEntry.th32ProcessID);
if( NULL == hProcess ) 
{
nNewProcess.m_strBinPath = "";
nNewProcess.m_bIsSystem = true;
nArray.push_back(nNewProcess);
continue;
}


GetModuleFileNameExA(hProcess, NULL, szPath, Utils::File::MAX_PATH_LEN);
szPath[Utils::File::MAX_PATH_LEN - 1] = 0;
nNewProcess.m_strBinPath = std::string(szPath);
nNewProcess.m_strDescribe = UtilsHelper::Instance().GetFileInfo("FileDescription", nNewProcess.m_strBinPath.c_str());


//nNewProcess.m_hIcon = ::ExtractIcon(NULL, nNewProcess.m_strBinPath.c_str(), 0);


PROCESS_MEMORY_COUNTERS nMemoryInfo = {0};
nMemoryInfo.cb = sizeof(nMemoryInfo);
if( GetProcessMemoryInfo(hProcess, &nMemoryInfo, sizeof(nMemoryInfo)) )
{
nNewProcess.m_nPhysicalMemorySize = nMemoryInfo.PeakWorkingSetSize;
nNewProcess.m_nVirtualMemorySize  = nMemoryInfo.WorkingSetSize;
}


FILETIME nCreationTime , nExitTime , nKernelTime , nUserTime;
if( GetProcessTimes(hProcess , &nCreationTime , &nExitTime , &nKernelTime , &nUserTime) )
{
nNewProcess.m_nUserTime = ((uint64)nUserTime.dwHighDateTime) << 32 | nUserTime.dwLowDateTime;
nNewProcess.m_nKernelTime = ((uint64)nKernelTime.dwHighDateTime) << 32 | nKernelTime.dwLowDateTime;
nNewProcess.m_nCreationTime = ((uint64)nCreationTime.dwHighDateTime) << 32 | nCreationTime.dwLowDateTime;
}


nNewProcess.m_bIsSystem = ( IsSysProcess(hProcess) == TRUE );
nArray.push_back(nNewProcess);
CloseHandle(hProcess);


}while( Process32Next(hSnapShot, &nProcessEntry) );

CloseHandle(hSnapShot);
return true;

此为公司代码的部分,,具体可用。。当时不能直接复制执行了。。只是做下备份

得到cpu占有率的API函数:
GetSystemTimes

得到内存使用情况的API函数:

GlobalMemoryStatusEx Function
         Retrieves information about the system's current usage of both physical and virtual memory.
GetPerformanceInfo Function
        Retrieves the performance values contained in the PERFORMANCE_INFORMATION structure
获取特定程序的内存使用情况用:
GetProcessMemoryInfo Function
         Retrieves information about the memory usage of the specified process.


我写的一个cpu使用率例子:


#define _WIN32_WINNT   0x0501

#include <Windows.h>

#include <iostream> 
using   namespace   std;

__int64 CompareFileTime ( FILETIME time1, FILETIME time2 )
{
       __int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime ;
       __int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime ;

       return   (b - a);
}
void main() 

HANDLE hEvent;
BOOL res ;

FILETIME preidleTime;
FILETIME prekernelTime;
FILETIME preuserTime;

FILETIME idleTime;
FILETIME kernelTime;
FILETIME userTime;

res = GetSystemTimes( &idleTime, &kernelTime, &userTime );

preidleTime = idleTime;
prekernelTime = kernelTime;
preuserTime = userTime ;

hEvent = CreateEvent (NULL,FALSE,FALSE,NULL); // 初始值为 nonsignaled ,并且每次触发后自动设置为nonsignaled

while (1){

      WaitForSingleObject( hEvent,1000 ); //等待500毫秒
      res = GetSystemTimes( &idleTime, &kernelTime, &userTime );
     
       int idle = CompareFileTime( preidleTime,idleTime);
       int kernel = CompareFileTime( prekernelTime, kernelTime);
       int user = CompareFileTime(preuserTime, userTime);

int cpu = (kernel +user - idle) *100/(kernel+user);
     int cpuidle = ( idle) *100/(kernel+user);
     cout << "CPU利用率:" << cpu << "%" << "      CPU空闲率:" <<cpuidle << "%" <<endl;

    preidleTime = idleTime;
    prekernelTime = kernelTime;
    preuserTime = userTime ;
}


}

运行效果如图:


MSDN中 获取内存使用情况的例子:

Example Code [C++]

The following code shows a simple use of the GlobalMemoryStatusEx function.

 

// Sample output:
// There is       51 percent of memory in use.
// There are 2029968 total Kbytes of physical memory.
// There are 987388 free Kbytes of physical memory.
// There are 3884620 total Kbytes of paging file.
// There are 2799776 free Kbytes of paging file.
// There are 2097024 total Kbytes of virtual memory.
// There are 2084876 free Kbytes of virtual memory.
// There are       0 free Kbytes of extended memory.

#include <windows.h>
#include <stdio.h>

// Use to convert bytes to KB
#define DIV 1024

// Specify the width of the field in which to print the numbers. 
// The asterisk in the format specifier "%*I64d" takes an integer 
// argument and uses it to pad and right justify the number.
#define WIDTH 7

void main(int argc, char *argv[])
{
MEMORYSTATUSEX statex;

statex.dwLength = sizeof (statex);

GlobalMemoryStatusEx (&statex);

printf ("There is %*ld percent of memory in use./n",
          WIDTH, statex.dwMemoryLoad);
printf ("There are %*I64d total Kbytes of physical memory./n",
          WIDTH, statex.ullTotalPhys/DIV);
printf ("There are %*I64d free Kbytes of physical memory./n",
          WIDTH, statex.ullAvailPhys/DIV);
printf ("There are %*I64d total Kbytes of paging file./n",
          WIDTH, statex.ullTotalPageFile/DIV);
printf ("There are %*I64d free Kbytes of paging file./n",
          WIDTH, statex.ullAvailPageFile/DIV);
printf ("There are %*I64d total Kbytes of virtual memory./n",
          WIDTH, statex.ullTotalVirtual/DIV);
printf ("There are %*I64d free Kbytes of virtual memory./n",
          WIDTH, statex.ullAvailVirtual/DIV);

// Show the amount of extended memory available.

printf ("There are %*I64d free Kbytes of extended memory./n",
          WIDTH, statex.ullAvailExtendedVirtual/DIV);
}

MSDN中获取特定程序内存使用情况的例子:

Collecting Memory Usage Information For a Process

To determine the efficiency of your application, you may want to examine its memory usage. The following sample code uses the GetProcessMemoryInfo function to obtain information about the memory usage of a process.

#include <windows.h>
#include <stdio.h>
#include <psapi.h>

void PrintMemoryInfo( DWORD processID )
{
    HANDLE hProcess;
    PROCESS_MEMORY_COUNTERS pmc;

    // Print the process identifier.

    printf( "/nProcess ID: %u/n", processID );

    // Print information about the memory usage of the process.

    hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION |
                                    PROCESS_VM_READ,
                                    FALSE, processID );
    if (NULL == hProcess)
        return;

    if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )
    {
        printf( "/tPageFaultCount: 0x%08X/n", pmc.PageFaultCount );
        printf( "/tPeakWorkingSetSize: 0x%08X/n", 
                  pmc.PeakWorkingSetSize );
        printf( "/tWorkingSetSize: 0x%08X/n", pmc.WorkingSetSize );
        printf( "/tQuotaPeakPagedPoolUsage: 0x%08X/n", 
                  pmc.QuotaPeakPagedPoolUsage );
        printf( "/tQuotaPagedPoolUsage: 0x%08X/n", 
                  pmc.QuotaPagedPoolUsage );
        printf( "/tQuotaPeakNonPagedPoolUsage: 0x%08X/n", 
                  pmc.QuotaPeakNonPagedPoolUsage );
        printf( "/tQuotaNonPagedPoolUsage: 0x%08X/n", 
                  pmc.QuotaNonPagedPoolUsage );
        printf( "/tPagefileUsage: 0x%08X/n", pmc.PagefileUsage ); 
        printf( "/tPeakPagefileUsage: 0x%08X/n", 
                  pmc.PeakPagefileUsage );
    }

    CloseHandle( hProcess );
}

int main( )
{
    // Get the list of process identifiers.

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        return 1;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the memory usage for each process

    for ( i = 0; i < cProcesses; i++ )
        PrintMemoryInfo( aProcesses[i] );

    return 0;
}//这个还需要添加库包含psapi.lib才能编译过
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Windows获取CPU使用率可以使用PerformanceCounter类和ManagementObject类来实现。 首先,可以使用PerformanceCounter类从计算机性能计数器获取CPU使用率。通过实例化PerformanceCounter类并指定相关的性能计数器类别和计数器名称,可以获取CPU使用率。代码示例如下: ```csharp PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); float cpuUsage = cpuCounter.NextValue() / Environment.ProcessorCount; System.Threading.Thread.Sleep(1000); // 等待1秒 cpuUsage = cpuCounter.NextValue() / Environment.ProcessorCount; Console.WriteLine("CPU使用率: " + cpuUsage.ToString("0.00") + "%"); ``` 以上代码实例化了PerformanceCounter类,并指定了Processor类别的"% Processor Time"计数器。通过调用NextValue()方法获取计数器的下一个值,然后除以ProcessorCount得到CPU使用率。为了获取到实时的CPU使用率,sleep方法会等待1秒钟再次获取值。最后将获取到的值输出。 另外一种方式是使用ManagementObject类从Windows Management Instrumentation (WMI) 获取CPU使用率。通过使用WQL (Windows Management Query Language) 查询语句来获取相关信息,代码示例如下: ```csharp ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor"); ManagementObjectCollection collection = searcher.Get(); foreach (ManagementObject obj in collection) { if (obj["Name"].ToString() == "_Total") { float cpuUsage = 100 - float.Parse(obj["PercentIdleTime"].ToString()); Console.WriteLine("CPU使用率: " + cpuUsage.ToString("0.00") + "%"); break; } } ``` 以上代码使用ManagementObjectSearcher类指定WQL查询语句,通过Get()方法获取到相关的性能数据。然后遍历获取到的集合,找到Name为"_Total"的对象,通过PercentIdleTime属性计算CPU使用率。 无论是使用PerformanceCounter类还是ManagementObject类,都能够获取到WindowsCPU使用率。具体使用哪种方式可以根据需要来选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值