利用Windows api获得CPU使用率
#include <windows.h>
#include <conio.h>
#include <stdio.h>
#define SystemBasicInformation 0
#define SystemPerformanceInformation 2
#define SystemTimeInformation 3
#define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
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;
typedef struct
{
LARGE_INTEGER liIdleTime;
DWORD dwSpare[76];
} SYSTEM_PERFORMANCE_INFORMATION;
typedef struct
{
LARGE_INTEGER liKeBootTime;
LARGE_INTEGER liKeSystemTime;
LARGE_INTEGER liExpTimeZoneBias;
ULONG uCurrentTimeZoneId;
DWORD dwReserved;
} SYSTEM_TIME_INFORMATION;
// ntdll!NtQuerySystemInformation (NT specific!)
//
// The function copies the system information of the
// specified type into a buffer
//
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQuerySystemInformation(
// IN UINT SystemInformationClass, // information type
// OUT PVOID SystemInformation, // pointer to buffer
// IN ULONG SystemInformationLength, // buffer size in bytes
// OUT PULONG ReturnLength OPTIONAL // pointer to a 32-bit
// // variable that receives
// // the number of bytes
// // written to the buffer
// );
typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
PROCNTQSI NtQuerySystemInformation;
void main(void)
{
SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
SYSTEM_TIME_INFORMATION SysTimeInfo;
SYSTEM_BASIC_INFORMATION SysBaseInfo;
double dbIdleTime;
double dbSystemTime;
LONG status;
LARGE_INTEGER liOldIdleTime = {0,0};
LARGE_INTEGER liOldSystemTime = {0,0};
NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
GetModuleHandle(“ntdll”),
“NtQuerySystemInformation”
);
if (!NtQuerySystemInformation)
return;
// get number of processors in the system
status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
if (status != NO_ERROR)
return;
printf(“\nCPU Usage (press any key to exit): “);
while(!_kbhit())
{
// get new system time
status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
if (status!=NO_ERROR)
return;
// get new CPU’s idle time
status = NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
if (status != NO_ERROR)
return;
// if it’s a first call – skip it
if (liOldIdleTime.QuadPart != 0)
{
// CurrentValue = NewValue – OldValue
dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) – Li2Double(liOldIdleTime);
dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) – Li2Double(liOldSystemTime);
// CurrentCpuIdle = IdleTime / SystemTime
dbIdleTime = dbIdleTime / dbSystemTime;
// CurrentCpuUsage% = 100 – (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime = 100.0 – dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
printf(“\b\b\b\b%3d%%”,(UINT)dbIdleTime);
}
// store new CPU’s idle and system time
liOldIdleTime = SysPerfInfo.liIdleTime;
liOldSystemTime = SysTimeInfo.liKeSystemTime;
// wait one second
Sleep(1000);
}
printf(“\n”);
}
NtQuerySystemInformation Function
[NtQuerySystemInformation may be altered or unavailable in future versions of Windows. Applications should use the alternate functions listed in this topic.]
Retrieves the specified system information.
Syntax
1
2
3
4
5
6 NTSTATUS WINAPI NtQuerySystemInformation(
__in SYSTEM_INFORMATION_CLASS <em>SystemInformationClass</em>,
__inout PVOID <em>SystemInformation</em>,
__in ULONG <em>SystemInformationLength</em>,
__out_opt PULONG <em>ReturnLength</em>
);
Parameters
- SystemInformationClass [in]
- One of the values enumerated in SYSTEM_INFORMATION_CLASS, which indicate the kind of system information to be retrieved. These include the following values.
- SystemBasicInformation
- Returns the number of processors in the system in a SYSTEM_BASIC_INFORMATION structure. Use the GetSystemInfo function instead.
- SystemPerformanceInformation
- Returns an opaque SYSTEM_PERFORMANCE_INFORMATION structure that can be used to generate an unpredictable seed for a random number generator. Use the CryptGenRandom function instead.
- SystemTimeOfDayInformation
- Returns an opaque SYSTEM_TIMEOFDAY_INFORMATION structure that can be used to generate an unpredictable seed for a random number generator. Use theCryptGenRandom function instead.
- SystemProcessInformation
- Returns an array of SYSTEM_PROCESS_INFORMATION structures, one for each process running in the system.
These structures contain information about the resource usage of each process, including the number of handles used by the process, the peak page-file usage, and the number of memory pages that the process has allocated.
- SystemProcessorPerformanceInformation
- Returns an array of SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION structures, one for each processor installed in the system.
- SystemInterruptInformation
- Returns an opaque SYSTEM_INTERRUPT_INFORMATION structure that can be used to generate an unpredictable seed for a random number generator. Use theCryptGenRandom function instead.
- SystemExceptionInformation
- Returns an opaque SYSTEM_EXCEPTION_INFORMATION structure that can be used to generate an unpredictable seed for a random number generator. Use theCryptGenRandom function instead.
- SystemRegistryQuotaInformation
- Returns a SYSTEM_REGISTRY_QUOTA_INFORMATION structure.
- SystemLookasideInformation
- Returns an opaque SYSTEM_LOOKASIDE_INFORMATION structure that can be used to generate an unpredictable seed for a random number generator. Use theCryptGenRandom function instead.
- SystemVhdBootInformation
- Returns a SYSTEM_VHD_BOOT_INFORMATION structure.
- SystemInformation [in, out]
- A pointer to a buffer that receives the requested information. The size and structure of this information varies depending on the value of the SystemInformationClassparameter:
- SYSTEM_BASIC_INFORMATION
- When the SystemInformationClass parameter is SystemBasicInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold a single SYSTEM_BASIC_INFORMATION structure having the following layout:1
2
3
4
5typedef struct _SYSTEM_BASIC_INFORMATION {
BYTE Reserved1[24];
PVOID Reserved2[4];
CCHAR NumberOfProcessors;
} SYSTEM_BASIC_INFORMATION;The NumberOfProcessors member contains the number of processors present in the system. Use GetSystemInfo instead to retrieve this information.
The other members of the structure are reserved for internal use by the operating system.
- SYSTEM_PERFORMANCE_INFORMATION
- When the SystemInformationClass parameter is SystemPerformanceInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an opaque SYSTEM_PERFORMANCE_INFORMATION structure for use in generating an unpredictable seed for a random number generator. For this purpose, the structure has the following layout:1
2
3typedef struct _SYSTEM_PERFORMANCE_INFORMATION {
BYTE Reserved1[312];
} SYSTEM_PERFORMANCE_INFORMATION;Individual members of the structure are reserved for internal use by the operating system.
Use the CryptGenRandom function instead to generate cryptographically random data.
- SYSTEM_TIMEOFDAY_INFORMATION
- When the SystemInformationClass parameter is SystemTimeOfDayInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an opaque SYSTEM_TIMEOFDAY_INFORMATION structure for use in generating an unpredictable seed for a random number generator. For this purpose, the structure has the following layout:1
2
3typedef struct _SYSTEM_TIMEOFDAY_INFORMATION {
BYTE Reserved1[48];
} SYSTEM_TIMEOFDAY_INFORMATION;Individual members of the structure are reserved for internal use by the operating system.
Use the CryptGenRandom function instead to generate cryptographically random data.
- SYSTEM_PROCESS_INFORMATION
- When the SystemInformationClass parameter is SystemProcessInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an array that contains as many SYSTEM_PROCESS_INFORMATION structures as there are processes running in the system. Each structure has the following layout:1
2
3
4
5
6
7
8
9
10
11
12
13typedef struct _SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryOffset;
BYTE Reserved1[52];
PVOID Reserved2[3];
HANDLE UniqueProcessId;
PVOID Reserved3;
ULONG HandleCount;
BYTE Reserved4[4];
PVOID Reserved5[11];
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
LARGE_INTEGER Reserved6[6];
} SYSTEM_PROCESS_INFORMATION;The start of the next item in the array is the address of the previous item plus the value in the NextEntryOffset member. For the last item in the array,NextEntryOffset is 0.
The HandleCount member contains the total number of handles being used by the process in question; use GetProcessHandleCount to retrieve this information instead.
The PeakPagefileUsage member contains the maximum number of bytes of page-file storage used by the process, and the PrivatePageCount member contains the number of memory pages allocated for the use of this process.
You can also retrieve this information using either the GetProcessMemoryInfo function or the Win32_Process class.
The other members of the structure are reserved for internal use by the operating system.
- SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
- When the SystemInformationClass parameter is SystemProcessorPerformanceInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an array that contains as many SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION structures as there are processors (CPUs) installed in the system. Each structure has the following layout:1
2
3
4
5
6
7
8typedef struct
_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
LARGE_INTEGER IdleTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER Reserved1[2];
ULONG Reserved2;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;The IdleTime member contains the amount of time that the system has been idle, in 100-nanosecond intervals.
The KernelTime member contains the amount of time that the system has spent executing in Kernel mode (including all threads in all processes, on all processors), in 100-nanosecond intervals.
The UserTime member contains the amount of time that the system has spent executing in User mode (including all threads in all processes, on all processors), in 100-nanosecond intervals.
Use GetSystemTimes instead to retrieve this information.
- SYSTEM_INTERRUPT_INFORMATION
- When the SystemInformationClass parameter is SystemInterruptInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an array that contains as many opaque SYSTEM_INTERRUPT_INFORMATION structures as there are processors (CPUs) installed on the system. Each structure, or the array as a whole, can be used to generate an unpredictable seed for a random number generator. For this purpose, the structure has the following layout:1
2
3typedef struct _SYSTEM_INTERRUPT_INFORMATION {
BYTE Reserved1[24];
} SYSTEM_INTERRUPT_INFORMATION;Individual members of the structure are reserved for internal use by the operating system.
Use the CryptGenRandom function instead to generate cryptographically random data.
- SYSTEM_EXCEPTION_INFORMATION
- When the SystemInformationClass parameter is SystemExceptionInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an opaque SYSTEM_EXCEPTION_INFORMATION structure for use in generating an unpredictable seed for a random number generator. For this purpose, the structure has the following layout:1
2
3typedef struct _SYSTEM_EXCEPTION_INFORMATION {
BYTE Reserved1[16];
} SYSTEM_EXCEPTION_INFORMATION;Individual members of the structure are reserved for internal use by the operating system.
Use the CryptGenRandom function instead to generate cryptographically random data.
- SYSTEM_REGISTRY_QUOTA_INFORMATION
- When the SystemInformationClass parameter is SystemRegistryQuotaInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold a single SYSTEM_REGISTRY_QUOTA_INFORMATION structure having the following layout:1
2
3
4
5typedef struct _SYSTEM_REGISTRY_QUOTA_INFORMATION {
ULONG RegistryQuotaAllowed;
ULONG RegistryQuotaUsed;
PVOID Reserved1;
} SYSTEM_REGISTRY_QUOTA_INFORMATION;The RegistryQuotaAllowed member contains the maximum size, in bytes, that the Registry can attain on this system.
The RegistryQuotaUsed member contains the current size of the Registry, in bytes.
Use GetSystemRegistryQuota instead to retrieve this information.
The other member of the structure is reserved for internal use by the operating system.
- SYSTEM_LOOKASIDE_INFORMATION
- When the SystemInformationClass parameter is SystemLookasideInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold an opaque SYSTEM_LOOKASIDE_INFORMATION structure for use in generating an unpredictable seed for a random number generator. For this purpose, the structure has the following layout:1
2
3typedef struct _SYSTEM_LOOKASIDE_INFORMATION {
BYTE Reserved1[32];
} SYSTEM_LOOKASIDE_INFORMATION;Individual members of the structure are reserved for internal use by the operating system.
Use the CryptGenRandom function instead to generate cryptographically random data.
- SYSTEM_VHD_BOOT_INFORMATION
- When the SystemInformationClass parameter is SystemVhdBootInformation, the buffer pointed to by the SystemInformation parameter should be large enough to hold a single SYSTEM_VHD_BOOT_INFORMATION structure having the following layout:1
2
3
4
5typedef struct _SYSTEM_VHD_BOOT_INFORMATION {
BOOLEAN OsDiskIsVhd;
ULONG OsVhdFilePathOffset;
WCHAR OsVhdParentVolume[ANYSIZE_ARRAY];
} SYSTEM_VHD_BOOT_INFORMATION, *PSYSTEM_VHD_BOOT_INFORMATION;The OsDiskIsVhd member is TRUE if the disk is a virtual hard disk (VHD).
The OsVhdFilePathOffset member specifies a zero-based offset to the relative VHD file name in the string specified by OsVhdParentVolume, in characters. For example, the offset to “\vhd\os.vhd” in “\Device\HarddiskVolume2\vhd\os.vhd” would be 23.
The OsVhdParentVolume member specifies the path to the VHD file, including the volume, as a null-terminated string in file path format. For example: “\Device\HarddiskVolume2\vhd\os.vhd”.
- SystemInformationLength [in]
- The size of the buffer pointed to by the SystemInformation parameter, in bytes.
- ReturnLength [out, optional]
- An optional pointer to a location where the function writes the actual size of the information requested. If that size is less than or equal to the SystemInformationLengthparameter, the function copies the information into the SystemInformation buffer; otherwise, it returns an NTSTATUS error code and returns in ReturnLength the size of buffer required to receive the requested information.
Return Value
Returns an NTSTATUS success or error code.
The forms and significance of NTSTATUS error codes are listed in the Ntstatus.h header file available in the DDK, and are described in the DDK documentation.
Remarks
The NtQuerySystemInformation function and the structures that it returns are internal to the operating system and subject to change from one release of Windows to another. To maintain the compatibility of your application, it is better to use the alternate functions previously mentioned instead.
If you do use NtQuerySystemInformation, access the function through run-time dynamic linking. This gives your code an opportunity to respond gracefully if the function has been changed or removed from the operating system. Signature changes, however, may not be detectable.
This function has no associated import library. You must use the LoadLibrary and GetProcAddress functions to dynamically link to Ntdll.dll.
Requirements
| Header | Winternl.h |
|---|---|
| DLL | Ntdll.dll |
Leave a comment