san*_*ani 5 c c++ windows monitoring
如何计算另一个并发程序的CPU和磁盘利用率?即一个程序正在运行,其他程序计算第一个资源的使用.
我正在使用C和C++并在Windows XP下运行.
Ser*_*kov 10
至于CPU利用率,看看这个链接后不难做到Windows C++获取性能计数器的CPU和内存利用率.据我所知(但尚未测试),也可以找出磁盘利用率.
我们的想法是使用性能计数器.在您的情况下,您需要将性能计数器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:
;
}
Run Code Online (Sandbox Code Playgroud)
还有一件事需要提及.PdhExpandWildCardPath允许您L"\\Process(*)\\% Processor Time"在计算机上运行的进程列表中展开这样的字符串.然后,您可以查询每个进程的性能计数器.
这是可能的,因为 Process Explorer 可以做到这一点,但我认为您将不得不使用某种未记录的 Windows API。PSAPI 有点接近,但它只提供内存使用信息,而不提供 CPU 或磁盘利用率。
| 归档时间: |
|
| 查看次数: |
10200 次 |
| 最近记录: |