利用未公布API获取CPU使用率

利用ntdll.dll中没有公开的API函数: NtQuerySystemInformation

typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
    PROCNTQSI NtQuerySystemInformation;

    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;
}
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 (m_liOldIdleTime.QuadPart != 0)
     {
         // CurrentValue = NewValue - OldValue
         dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(m_liOldIdleTime);
         dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(m_liOldSystemTime);

          // CurrentCpuIdle = IdleTime / SystemTime
          dbIdleTime = dbIdleTime / dbSystemTime;

          // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
          dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;

          m_fNewUsges = (UINT)dbIdleTime;
     }


你可能感兴趣的:(利用未公布API获取CPU使用率)