1. An Implicit Function in Ntdll. dll can be used in an operating system after 2 K.
In Windows NT/2000, the method for obtaining CPU usage is different from that in Windows 9X. in Windows NT/2000, the "performance counter" is not used to obtain CPU usage ". Instead, it uses ntquerysysteminformation, an API function not publicly available in Ntdll. dll. For more information about its usage, see Article : How to obtain the system startup time in Windows NT/2000.
To calculate the CPU usage in Windows NT/2000, use the following formula:
Cpuusageinpercent = 100-(cputimen-CpuTimen-1-cputime0)/(systemtimen-SystemTimen-1-systemtime0)/numberofprocessors * 100
Here
CPU time is the idle time of the CPU (in milliseconds );
Systemtime is the system time (MS );
Numberofprocessors indicates the number of processors in the system;
0, 1, n indicates the number of samples (0 indicates the oldest sampling, 1 indicates the newest sampling, and N indicates the newest sampling );
The following describes the required parameter values for calling the ntquerysysteminformation function. First, obtain the number of processors. In the system_basic_information structure, there is a bkenumberprocessors Member, which is what we need.
# 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 );
To implement multiple sampling, We need to query the cputime and systemtime values in a loop and store their old values in temporary variables. For how to obtain the system time, see how to obtain the system startup time in Windows NT/2000. The idle time of the CPU is stored in the liidletime Member of the system_performance_information structure.
# 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 );
}