Windows NT/2000中擷取CPU使用率

來源:互聯網
上載者:User
Windows NT/2000中擷取CUP使用率的方法與Windows 9x系統中所使用的方法不同,Windows NT/2000中擷取CUP使用率不用"效能計數器"。而是使用一個NTDLL.DLL中未公開的API函數--NtQuerySystemInformation。它的使用方法參見另外一篇文章:《Windows NT/2000系統中如何擷取系統的啟動時間》。

為了計算Windows NT/2000系統中CPU的使用率,我們使用下面的公式:

CpuUsageInPercent = 100 - (CpuTimen - CpuTimen-1 - CpuTime0) / (SystemTimen - SystemTimen-1 - SystemTime0) / NumberOfProcessors * 100

這裡
CpuTime為CPU的空閑時間(毫秒);
SystemTime為系統時間(毫秒);
NumberOfProcessors為系統中處理器的數量;
0,1,n 表示取樣數(0指最老的取樣,1 指最近的取樣,n 指最新的取樣);

下面我們來求出調用NtQuerySystemInformation函數所必要參數值。首先求出處理器數量值,SYSTEM_BASIC_INFORMATION結構中有一個bKeNumberProcessors成員,它就是我們所需要的。

#define SystemBasicInformation 0

typedef struct
{
  DWORD dwUnknown1;
  ULONG uKeMaximumIncrement;
  ULONG uPageSize;
  ULONG uMmNumberOfPhysicalPages;
  ULONG uMmLowestPhysicalPage;
  ULONG uMmHighestPhysicalPage;
  ULONG uAllocationGranularity;
  PVOID pLowestUserAddress;
  PVOID pMmHighestUserAddress;
  ULONG uKeActiveProcessors;
  BYTE bKeNumberProcessors;
  BYTE bUnknown2;
  WORD wUnknown3;
} SYSTEM_BASIC_INFORMATION;

LONG status;
SYSTEM_BASIC_INFORMATION Sbi;

status =  NtQuerySystemInformation(SystemBasicInformation,&Sbi,sizeof(Sbi),0);  

為了實現多個取樣,我們需要在迴圈中論詢CpuTime 和 SystemTime的值並將它們的舊的值儲存在臨時變數中。有關如何擷取系統時間的方法請參見:<a href="http://www.vckbase.com/bbs/prime/viewprime_mng.asp?id=348">《Windows NT/2000系統中如何擷取系統的啟動時間》</a>。CPU的空閑時間儲存在SYSTEM_PERFORMANCE_INFORMATION結構的liIdleTime 成員中。

#define SystemPerformanceInformation 2

typedef struct
{
  LARGE_INTEGER liIdleTime;
  DWORD dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;

LARGE_INTEGER liOldIdleTime = {0,0};
LARGE_INTEGER liOldSystemTime = {0,0};
SYSTEM_PERFORMANCE_INFORMATION Spi;

while (1) {
status =  NtQuerySystemInformation(SystemTimeInformation,&Sti,sizeof(Sti),0);  
status =  NtQuerySystemInformation(SystemPerformanceInformation,&Spi,sizeof(Spi),0);  

// calculate the CPU usage here

liOldIdleTime = Spi.liIdleTime;
liOldSystemTime = Sti.liKeSystemTime;

Sleep(1000);
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.