Delphi 获得每个进程的CPU使用率


本文整理自网络,侵删。

 function GetCPUUsage(var liOldIdleTime, liOldSystemTime: LARGE_INTEGER): string;
type
  TSystem_Basic_Information = packed record
    dwUnknown1: DWORD;
    uKeMaximumIncrement: ULONG;
    uPageSize: ULONG;
    uMmNumberOfPhysicalPages: ULONG;
    uMmLowestPhysicalPage: ULONG;
    uMmHighestPhysicalPage: ULONG;
    uAllocationGranularity: ULONG;
    pLowestUserAddress: Pointer;
    pMmHighestUserAddress: Pointer;
    uKeActiveProcessors: ULONG;
    bKeNumberProcessors: byte;
    bUnknown2: byte;
    wUnknown3: word;
  end;

  TSystem_Performance_Information = packed record
    liIdleTime: LARGE_INTEGER; {LARGE_INTEGER}
    dwSpare: array[0..75] of DWORD;
  end;

  TSystem_Time_Information = packed record
    liKeBootTime: LARGE_INTEGER;
    liKeSystemTime: LARGE_INTEGER;
    liExpTimeZoneBias: LARGE_INTEGER;
    uCurrentTimeZoneId: ULONG;
    dwReserved: DWORD;
  end;

  TNtQuerySystemInformation = function(infoClass: DWORD; buffer: Pointer; bufSize: DWORD; var returnSize: Dword): DWORD; stdcall;
var
  NtQuerySystemInformation: TNtQuerySystemInformation;
  SysBaseInfo: TSystem_Basic_Information;
  SysPerfInfo: TSystem_Performance_Information;
  SysTimeInfo: TSystem_Time_Information;
  status: DWORD; {long}
  dbSystemTime: Double;
  dbIdleTime: Double;
begin
  Result := '<N/A>';

  NtQuerySystemInformation := GetProcAddress(GetModuleHandle('ntdll.dll'), 'NtQuerySystemInformation');
  if @NtQuerySystemInformation = nil then Exit;
  
  if (NtQuerySystemInformation(0, @SysBaseInfo, SizeOf(SysBaseInfo), status) <> 0)
    or (NtQuerySystemInformation(3, @SysTimeInfo, SizeOf(SysTimeInfo), status) <> 0)
    or (NtQuerySystemInformation(2, @SysPerfInfo, SizeOf(SysPerfInfo), status) <> 0) then Exit;

  if liOldIdleTime.QuadPart <> 0 then
  begin
    // CurrentValue = NewValue - OldValue
    dbIdleTime := Int64(SysPerfInfo.liIdleTime) - Int64(liOldIdleTime);
    dbSystemTime := Int64(SysTimeInfo.liKeSystemTime) - Int64(liOldSystemTime);

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

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

    // Show Percentage
    Result := FormatFloat('0.00 %',dbIdleTime);
  end;
  liOldIdleTime := SysPerfInfo.liIdleTime;
  liOldSystemTime := SysTimeInfo.liKeSystemTime;
end;

相关阅读 >>

Delphi 判断某个系统服务是否存在及相关状态

Delphi10.3构造一个json数据的第三种方法,并格式化输出

Delphi unigui 获取files路径

Delphi 如何让scrollbox的内容与滚动条一起实时滚动

Delphi 顺序查找与二分查找

Delphi renamefile 文件改名

Delphi多级指针

Delphi禁止用户切换任务

Delphi tgauge类的定义在哪个单元中定义的?

Delphi mscomm 发送接收

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...