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

时间:2010-03-19 06:18:28

标签: c++ c windows monitoring

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

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

2 个答案:

答案 0 :(得分:10)

关于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"的字符串。然后,您可以查询每个流程的性能计数器。

答案 1 :(得分:1)

有可能,正如Process Explorer可以做到的那样,但我认为你将不得不使用某种未记录的Windows API。 PSAPI有点接近,但它只提供内存使用信息,而不是CPU或磁盘利用率。