2010-03-19 42 views
5

如何計算另一個併發程序的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

回答

1

這是可能的,因爲Process Explorer可以做到這一點,但我認爲你將不得不使用某種未公開的Windows API。 PSAPI有些接近,但它只提供內存使用信息,而不是CPU或磁盤利用率。

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"。然後你可以查詢每個進程的性能計數器。