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.

相关阅读 >>

Delphi 中相对路径与绝对路径函数

Delphi 单击按钮左键弹起菜单

Delphi 如何使用 ppchar

Delphi读取xml文件

Delphi 精炼的数字转换人民币大写转换代码

Delphi 实现延时自动关闭对话框

Delphi 使用indy解决tidssliohandlersocketopenssl could not load ssl library错误

Delphi防止因系统崩溃而丢失任务栏的图标(重建托盘图标)

Delphi 对比时间的函数

Delphi inc函数和dec函数的用法

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



打赏

取消

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

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

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

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

评论

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