监控单个程序的CPU和磁盘利用率

问题描述:

如何计算另一个并发程序的CPU和磁盘利用率?即一个程序正在运行,另一个程序计算第一个资源的使用。监控单个程序的CPU和磁盘利用率

我使用C和C++并在Windows XP下运行。

+5

“我想要的代码”是您在公司程序员经理时所说的话。你知道,工作。我们帮助,而不是工作。 :) – GManNickG 2010-03-19 06:23:01

+1

GMan:太对了。我有没有这样做过,我的眼睛现在重新解释了?我认为非英语用户在表示他们需要帮助或知道哪些API(“代码”)有用时通常会使用该短语。 – 2010-03-19 06:28:08

+0

'top'? ______ – kennytm 2010-03-19 06:29:04

这是可能的,因为Process Explorer可以做到这一点,但我认为你将不得不使用某种未公开的Windows API。 PSAPI有些接近,但它只提供内存使用信息,而不是CPU或磁盘利用率。

至于CPU利用率,看看这个链接Windows C++ Get CPU and Memory Utilisation With Performance Counters后不难做到。据我了解(但还没有测试),也可以找出磁盘利用率。

这个想法是使用Performance Counters。在您的情况下,您需要将性能计数器L"\\Process(program_you_are_interested_in_name)\\% Processor Time"用于CPU利用率,并可能使用性能计数器L"\\Process(program_you_are_interested_in_name)\\Data Bytes/sec"进行磁盘操作。由于我不确定您需要了解磁盘操作的哪些参数,所以您可以自己查看所有可用参数的列表:Process Object

例如,如果您有名为a_program_name.exe的并发程序,则可以找到它CPU利用率至少测量性能计数器的两倍L"\\Process(a_program_name)\\% Processor Time"。在这个例子中,它是在一个循环中完成的。顺便说一下,使用此测试测量在多核处理器上运行的多线程应用程序可能会使CPU利用率超过100%。

#include <iostream> 
#include <windows.h> 
#include <stdio.h> 
#include <pdh.h> 
#include <pdhmsg.h> 
#include <string.h> 
#include <string> 
#include <iostream> 

// Put name of your process here!!!! 
CONST PWSTR COUNTER_PATH = L"\\Process(a_program_name)\\% Processor Time"; 

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

    PDH_HQUERY hquery; 
    PDH_HCOUNTER hcountercpu; 
    PDH_STATUS status; 
    LPSTR pMessage; 
    PDH_FMT_COUNTERVALUE countervalcpu; 

    if((status=PdhOpenQuery(NULL, 0, &hquery))!=ERROR_SUCCESS){ 
     printf("PdhOpenQuery %lx\n", status);  
     goto END; 
    } 

    if((status=PdhAddCounter(hquery,COUNTER_PATH,0, &hcountercpu))!=ERROR_SUCCESS){ 
      printf("PdhAddCounter (cpu) %lx\n", status);  
      goto END; 
    } 

    /*Start outside the loop as CPU requires difference 
    between two PdhCollectQueryData s*/ 
    if((status=PdhCollectQueryData(hquery))!=ERROR_SUCCESS){ 
     printf("PdhCollectQueryData %lx\n", status);  
     goto END; 
    } 

    while(true){ 
     if((status=PdhCollectQueryData(hquery))!=ERROR_SUCCESS){ 
      printf("PdhCollectQueryData %lx\n", status);  
      goto END; 
     } 

     if((status=PdhGetFormattedCounterValue(hcountercpu, PDH_FMT_LONG | PDH_FMT_NOCAP100, 0, &countervalcpu))!=ERROR_SUCCESS){ 
       printf("PdhGetFormattedCounterValue(cpu) %lx\n", status);  
       goto END; 
     } 

     printf("cpu %3d%%\n", countervalcpu.longValue); 

     Sleep(1000); 

    } 
END: 
    ; 
} 

还有一件事要提。 PdhExpandWildCardPath可让您在计算机上运行的进程列表中展开这样的字符串,例如L"\\Process(*)\\% Processor Time"。然后你可以查询每个进程的性能计数器。