//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
1条答案
按热度按时间tct7dpnv1#
下面是一个函数,它将(任何进程的)进程id作为输入,并将该进程的CPU百分比作为输出。
在一条注解中,op询问是否只有一个命令行可以执行,以获取CPU百分比。以下是针对命令行的解决方案:
和
其中5332是进程ID。
但是,如果您要使用WMIC来获取CPU百分比,那么最好使用Delphi内部的WMI对象(使用OLE对象)。