delphi进程的CPU占比计算

type
  TProcessCpuUsage = record
  private
    FLastUsed, FLastTime: Int64;
    FCpuCount: Integer;
  public
    class function Create: TProcessCpuUsage; static;
    function Current(ProcessID: DWORD): Single;
  end;

class function TProcessCpuUsage.Create: TProcessCpuUsage;
begin
  Result.FLastTime := 0;
  Result.FLastUsed := 0;
end;

function TProcessCpuUsage.Current(ProcessID: DWORD): Single;
var
  Usage, ACurTime: UInt64;
  CreateTime, ExitTime, IdleTime, UserTime, KernelTime: TFileTime;
  hProcess: THandle;
  CpuCount: Integer;

//FileTime转化为Int64
  function FileTimeToI64(const ATime: TFileTime): Int64;
  begin
    Result := (Int64(ATime.dwHighDateTime) shl 32) + ATime.dwLowDateTime;
  end;
//获取逻辑CPU数量
  function GetCPUCount: Integer;
  var
    SysInfo: TSystemInfo;
  begin
    GetSystemInfo(SysInfo);
    Result := SysInfo.dwNumberOfProcessors;
  end;

begin
  Result := 0;
  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ProcessID);
  if GetProcessTimes(hProcess, CreateTime, ExitTime, KernelTime, UserTime) then
  begin
    ACurTime := GetTickCount;
    Usage := FileTimeToI64(UserTime) + FileTimeToI64(KernelTime);
    CpuCount := GetCPUCount;
    if (FLastTime <> 0) then
//(这次使用量 - 上一次使用量)  / (这次时间-上一次时间)/逻辑CPU核数
      Result := (Usage - FLastUsed) / (ACurTime - FLastTime) / FCpuCount / 100;
    FLastUsed := Usage;
    FLastTime := ACurTime;
  end;
end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值