如何获取应用程序进程的即时CPU使用率

yebdmbv4  于 2022-09-21  发布在  其他
关注(0)|答案(1)|浏览(202)

我现在需要获得我自己的应用程序进程中的CPU使用率百分比,与Windows任务管理器中的CPU列显示的值完全相同,但使用的是Delphi 11。这可能吗?

我在so中找到了一些示例,但它们都获得了全局CPU使用率,而不是特定的进程。

tct7dpnv

tct7dpnv1#

下面是一个函数,它将(任何进程的)进程id作为输入,并将该进程的CPU百分比作为输出。

//A function that returns CPU usage (in percent) for a given process id
function GetCpuUsage(PID:cardinal):single;
const
    cWaitTime=750;
var
    h: Cardinal;
    mCreationTime,mExitTime,mKernelTime, mUserTime: _FILETIME;
    TotalTime1,TotalTime2: Int64;
    SysInfo : _SYSTEM_INFO;
    CpuCount: Word;
begin
    //We need to know the number of CPUs and divide the result by that, otherwise we will get wrong percentage on multi-core systems
    GetSystemInfo(SysInfo);
    CpuCount := SysInfo.dwNumberOfProcessors;

    //We need to get a handle of the process with PROCESS_QUERY_INFORMATION privileges.
    h:=OpenProcess(PROCESS_QUERY_INFORMATION,false,PID);
    //We can use the GetProcessTimes() function to get the amount of time the process has spent in kernel mode and user mode.
    GetProcessTimes(h,mCreationTime,mExitTime,mKernelTime,mUserTime);
    TotalTime1:=int64(mKernelTime.dwLowDateTime or (mKernelTime.dwHighDateTime shr 32)) + int64(mUserTime.dwLowDateTime or (mUserTime.dwHighDateTime shr 32));

    //Wait a little
    Sleep(cWaitTime);

    GetProcessTimes(h,mCreationTime,mExitTime,mKernelTime,mUserTime);
    TotalTime2:=int64(mKernelTime.dwLowDateTime or (mKernelTime.dwHighDateTime shr 32))+
    int64(mUserTime.dwLowDateTime or (mUserTime.dwHighDateTime shr 32));

    //This should work out nicely, as there were approx. 250 ms between the calls
    //and the result will be a percentage between 0 and 100
    Result:=((TotalTime2-TotalTime1)/cWaitTime)/100/CpuCount;
    CloseHandle(h);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  pid: Word;
begin
  pid := GetCurrentProcessId;
  Button1.Caption := FormatFloat('0%', GetCpuUsage(pid));
end;

在一条注解中,op询问是否只有一个命令行可以执行,以获取CPU百分比。以下是针对命令行的解决方案:

wmic /namespace:\rootcimv2 path Win32_PerfFormattedData_PerfProc_Process WHERE "IDProcess = 5332" GET PercentProcessorTime

wmic /namespace:\rootcimv2 path Win32_PerfFormattedData_PerfProc_Process WHERE "IDProcess = 5332" GET PercentUserTime

其中5332是进程ID。

但是,如果您要使用WMIC来获取CPU百分比,那么最好使用Delphi内部的WMI对象(使用OLE对象)。

相关问题