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

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

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

至于CPU利用率,看看这个链接Windows C ++获取CPU和内存利用率与性能计数器是不难的。 据我了解(但还没有测试),也可以找出磁盘利用率。

这个想法是使用性能计数器 。 在这种情况下,您需要为CPU使用率使用性能计数器L"\\Process(program_you_are_interested_in_name)\\% Processor Time" ,对于磁盘操作可能需要使用性能计数器L"\\Process(program_you_are_interested_in_name)\\% Processor Time" L"\\Process(program_you_are_interested_in_name)\\Data Bytes/sec" 。 由于我不确定你需要知道什么参数正确的磁盘操作,你可以看看所有可用的参数列表: 过程对象

例如,如果您有名为a_program_name.exe的并发程序,则可以找到至少测量两次性能计数器L"\\Process(a_program_name)\\% Processor Time" CPU利用率。 在这个例子中,它是在一个循环中完成的。 顺便说一下,使用此测试进行测试,在多核处理器上运行的多线程应用程序可能会使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" 。 然后你可以查询每个进程的性能计数器。

这是可能的,因为程序资源管理器可以做到这一点,但我认为你将不得不使用某种未公开的Windows API。 PSAPI有些接近,但它只给出内存使用情况信息,而不是CPU或磁盘利用率。