Delphi取CPU利用率

unit Agent;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
_SYSTEM_PERFORMANCE_INFORMATION = record
    IdleTime: LARGE_INTEGER;
    Reserved: array[0..75] of DWORD;
end;
PSystemPerformanceInformation = ^TSystemPerformanceInformation;
TSystemPerformanceInformation = _SYSTEM_PERFORMANCE_INFORMATION;

_SYSTEM_BASIC_INFORMATION = record
    Reserved1: array[0..23] of Byte;
    Reserved2: array[0..3] of Pointer;
    NumberOfProcessors: UCHAR;
end;
PSystemBasicInformation = ^TSystemBasicInformation;
TSystemBasicInformation = _SYSTEM_BASIC_INFORMATION;

_SYSTEM_TIME_INFORMATION = record
    KeBootTime: LARGE_INTEGER;
    KeSystemTime: LARGE_INTEGER;
    ExpTimeZoneBias: LARGE_INTEGER;
    CurrentTimeZoneId: ULONG;
end;
PSystemTimeInformation = ^TSystemTimeInformation;
TSystemTimeInformation = _SYSTEM_TIME_INFORMATION;


type
  TForm1 = class(TForm)
    Button1: TButton;
    Timer1: TTimer;
    Label1: TLabel;
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

function NtQuerySystemInformation(
SystemInformationClass: UINT;
SystemInformation: Pointer;
SystemInformationLength: ULONG;
ReturnLength: PULONG): Integer; stdcall; external 'ntdll.dll';


var
  Form1: TForm1;
  FOldIdleTime: LARGE_INTEGER;
  FOldSystemTime: LARGE_INTEGER;


implementation

{$R *.dfm}

function GetCPURate: Byte;
var
PerfInfo: TSystemPerformanceInformation;
TimeInfo: TSystemTimeInformation;
BaseInfo: TSystemBasicInformation;
IdleTime: INT64;
SystemTime: INT64;
begin
Result := 0;
if NtQuerySystemInformation(3, @TimeInfo, SizeOf(TimeInfo), nil) <> NO_ERROR then
    Exit;
if NtQuerySystemInformation(2, @PerfInfo, SizeOf(PerfInfo), nil) <> NO_ERROR then
    Exit;
if NtQuerySystemInformation(0, @BaseInfo, SizeOf(BaseInfo), nil) <> NO_ERROR then
    Exit;
if (FOldIdleTime.QuadPart <> 0) and (BaseInfo.NumberOfProcessors <> 0) then
begin
    IdleTime := PerfInfo.IdleTime.QuadPart - FOldIdleTime.QuadPart;
    SystemTime := TimeInfo.KeSystemTime.QuadPart - FOldSystemTime.QuadPart;
    if SystemTime <> 0 then
      Result := Trunc(100.0 - (IdleTime / SystemTime) * 100.0 / BaseInfo.NumberOfProcessors);
end;
FOldIdleTime := PerfInfo.IdleTime;
FOldSystemTime := TimeInfo.KeSystemTime;
end;

 

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  self.Label1.Caption := IntToStr(GetCPURate);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin

end;

end.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值