Grupos de Google ya no admite nuevas publicaciones ni suscripciones de Usenet. El contenido anterior sigue siendo visible.

Finding Per Process CPU Usage

Visto 927 veces
Saltar al primer mensaje no leído

Jason

no leída,
14 may 2003, 9:21:0614/5/03
a
Ok I have helped enough people on this newsgroup, time to pay up!!!
Below is a code sample of what I am trying to accomplish. I am
trying to find a processes cpu usage. I am soo close. I would like to
see code that would complete the


procedure GetTheProcessTimes(PID: integer);
var
PH: THandle;
hProcess: THandle;
lpCreationTime, lpExitTime, lpKernelTime, lpUserTime: TFileTime;
lpSystemTime: TSystemTime;
KernelDay, UserDay: integer;

Result, strHours: string;
MyCreationTime, MyKernelTime, MyUserTime : String;
ProcTime : TDateTime;


begin
Result := 'n/a';
inc(counter);

hProcess := PID;

PH := OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, hProcess);
if PH <> 0 then
try
GetProcessTimes(PH, lpCreationTime, lpExitTime, lpKernelTime, lpUserTime);


if Counter = 1 then begin
//Get the Creation time and format it the counter is just for testing to
prevent reading
//is value again
FileTimeToSystemTime(lpCreationTime, lpSystemTime);
KernelDay := lpSystemTime.wDay;
CreationTime := SystemTimeToDateTime(lpSystemTime);
MyCreationTime := TimeToStr(CreationTime);
//WriteLn(MyCreationTime);
end;

//Get the kernel time and format it
FileTimeToSystemTime(lpKernelTime, lpSystemTime);
KernelDay := lpSystemTime.wDay;
KernelTime := SystemTimeToDateTime(lpSystemTime);
MyKernelTime := TimeToStr(KernelTime);
//WriteLn(MyKernelTime);

//Get the user time and format it
FileTimeToSystemTime(lpUserTime, lpSystemTime);
UserDay := lpSystemTime.wDay;
UserTime := SystemTimeToDateTime(lpSystemTime);
MyUserTime := TimeToStr(UserTime);
//WriteLn(MyUserTime);

//Calculate the cpu time
ProcTime := (UserTime + KernelTime);


// How do I get the Per Process CPU Usage!!!!!
Answer := (CreationTime / ProcTime) *100;


finally
CloseHandle(PH);
end
end;


Ignacio Vazquez

no leída,
14 may 2003, 10:03:5814/5/03
a
"Jason" <in...@goff.nu> wrote in message
news:3ec24268$1...@newsgroups.borland.com...

> Ok I have helped enough people on this newsgroup, time to pay up!!!
> Below is a code sample of what I am trying to accomplish. I am
> trying to find a processes cpu usage. I am soo close. I would like to
> see code that would complete the
>
> [snip]

>
> // How do I get the Per Process CPU Usage!!!!!
> Answer := (CreationTime / ProcTime) *100;

How about:

GetSystemTime(@SysTime);
SystemTimeToFileTime(@SysTime, @Now);
Answer:=(Now-CreationTime)/ProcTime*100;

Hope That Helps,
Ignacio

John Herbster (TeamB)

no leída,
14 may 2003, 10:27:1014/5/03
a

"Jason" <in...@goff.nu> wrote
> ... I am trying to find a process's cpu usage.

> // How do I get the Per Process CPU Usage!
> Answer := (CreationTime / ProcTime) *100;

Jason, I did not read all of your code, but is this what you are
looking for?
Answer := ProcTime/(Now - CreationTime)*100;
where ProcTime is in units of days and/or fraction.

The normal TaskMonitor display uses smaller time chuncks
RealTime0 := RealTime1; ProcTime0 := ProcTime1;
{Get new process times and current time}
CpuPercent := 100*(ProcTime1 - ProcTime0)/(RealTime1 - RealTime0);
Where the units of ProcTimes and RealTimes are the same.

Regards, JohnH


Kristofer Skaug

no leída,
14 may 2003, 10:39:1814/5/03
a
"Jason" wrote:
> Below is a code sample of what I am trying to accomplish.

Sorry, I don't have time to check your code.
But FWIW I have some code here, based on a snippet I picked up at
www.codepile.com some years ago (link seems to be dead now).
It is based on an undocumented WinAPI call (NtQuerySystemInformation),
and contains some information related to dual processors that you perhaps
can use to your advantage.

HTH, Kristofer


unit CpuLoad;

interface

uses Windows,Classes,SysUtils;

//-----------------------------------------------------------------------
-------
// CPU LOAD MEASUREMENT CLASS (SINGLE-POINT SAMPLING)
//-----------------------------------------------------------------------
-------

type TSystemBasicInformation = packed record
dwUnknown1: DWORD; // SIC
uKeMaximumIncrement: ULONG; // Windows.pas: ULONG = Cardinal
uPageSize: ULONG; // idem for all DWORDs below
uMmNumberOfPhysicalPages: ULONG;
uMmLowestPhysicalPage: ULONG;
uMmHighestPhysicalPage: ULONG;
uAllocationGranularity: ULONG;
pLowestUserAddress: pointer; // PVOID
pMmHighestUserAddress: pointer; // PVOID
uKeActiveProcessors: ULONG; // Number of Active processors
bKeNumberProcessors: byte; // Total Number of processors
bUnknown2: byte;
wUnknown3: word;
end; // TSystemBasicInformation
type pSystemBasicInformation = ^TSystemBasicInformation;

type TSystemPerformanceInformation = packed record
liIdleTime: Int64;
dwSpare: array[0..75] of dword;
end; // TSystemPerformanceInformation
type pSystemPerformanceInformation = ^TSystemPerformanceInformation;

type TSystemTimeInformation = packed record
liKeBootTime: Int64;
liKeSystemTime: Int64;
liExpTimeZoneBias: Int64;
uCurrentTimeZoneId: ULONG;
dwReserved: DWORD;
end; // TSystemTimeInformation

type TCpuMonitor = class
private
Int64OldIdleTime,Int64OldSystemTime: Int64;
iNumberOfProcessors: Integer;
SysPerfInfo: TSystemPerformanceInformation;
SysTimeInfo: TSystemTimeInformation;
SysBaseInfo: TSystemBasicInformation;
public
constructor Create; virtual;
function GetCpuLoadPercent:dword;
property NumberOfProcessors:Integer read iNumberOfProcessors;
end;


implementation

const SYSTEM_BASIC_INFORMATION = 0;
SYSTEM_PERFORMANCE_INFORMATION = 2;
SYSTEM_TIME_INFORMATION = 3;

function NtQuerySystemInformation(
SystemInformationClass : UINT;
pSystemInfo : pointer;
SystemInformationLength : ULONG;
ReturnLength : PULONG ) // Optional, OUT
: Integer; stdcall; external 'Ntdll.dll';

{ TCpuMonitor }

constructor TCpuMonitor.Create;
begin
// Store new CPU's idle and system time
// Get System time
if NtQuerySystemInformation(SYSTEM_TIME_INFORMATION,
@SysTimeInfo,SizeOf(SysTimeInfo),nil)<>NO_ERROR then
Exit;
Int64OldSystemTime:=SysTimeInfo.liKeSystemTime-100;
// Get CPU's idle time
if NtQuerySystemInformation(SYSTEM_PERFORMANCE_INFORMATION,
@SysPerfInfo,SizeOf(SysPerfInfo),nil)<>NO_ERROR then
Exit;
Int64OldIdleTime:=SysPerfInfo.liIdleTime-100;
// Get number of processors in the system
if NtQuerySystemInformation(SYSTEM_BASIC_INFORMATION,
@SysBaseInfo,SizeOf(SysBaseInfo),nil)<>NO_ERROR then
Exit;
iNumberOfProcessors:=SysBaseInfo.bKeNumberProcessors;
end; // proc Create

function TCpuMonitor.GetCpuLoadPercent: dword;
var Int64IdleTime,Int64SystemTime: Int64;
begin
// Get new system time
NtQuerySystemInformation(SYSTEM_TIME_INFORMATION,
@SysTimeInfo,SizeOf(SysTimeInfo),nil);
// Get new CPU's idle time
NtQuerySystemInformation(SYSTEM_PERFORMANCE_INFORMATION,
@SysPerfInfo,SizeOf(SysPerfInfo),nil);
// CurrentValue = NewValue - OldValue
Int64IdleTime:=SysPerfInfo.liIdleTime - Int64OldIdleTime;
Int64SystemTime:=(SysTimeInfo.liKeSystemTime - Int64OldSystemTime)+1;
// +1 make sure this var can't be zero
// CurrentCpuIdle = IdleTime / SystemTime
Int64IdleTime:=(Int64IdleTime*100) div Int64SystemTime; // *100 for %
Result:=100-(Integer(Int64IdleTime) div iNumberOfProcessors);
// Store new CPU's idle and system time
Int64OldIdleTime:=SysPerfInfo.liIdleTime;
Int64OldSystemTime:=SysTimeInfo.liKeSystemTime;
if Result>100 then Result:=100; // v01.01.00 corrective clipoff,
end; // func GetCpuLoadPercent


Jason

no leída,
15 may 2003, 12:39:0615/5/03
a
"Jason" <in...@goff.nu> wrote in message
news:3ec24268$1...@newsgroups.borland.com...
> Ok I have helped enough people on this newsgroup, time to pay up!!!
> Below is a code sample of what I am trying to accomplish. I am
> trying to find a processes cpu usage. I am soo close.

Here is some C Code that supposly does it. However I do not understand it
I found it on the internet. Thank-you John and Ignacio, but I am still a
little gray
on this subject....


*Note, the code is ment to run with other variables in my program, so it
needs to be hacked a bit for anyone else to use it*


float CFalconDlg::GetIdleTime()
{
static Once=0;
static FILETIME lastUserTime;
static FILETIME lastKernalTime;
FILETIME KernalTime, UserTime;

FILETIME Enter, Exit;

const size_t c_nMaxProc = 4096;
int x=0;
DWORD a_dwProcIds[c_nMaxProc + 1];
DWORD uResult = 0;
DWORD nEnumProc = 0;

static LARGE_INTEGER Kernal, User, lastKernal, lastUser;
LARGE_INTEGER sumKernal, sumUser;
sumKernal.QuadPart=0;
sumUser.QuadPart=0;
int ProcCount=0;
int MaxCount=0;

if (EnumProcesses(a_dwProcIds, c_nMaxProc * sizeof(DWORD), &nEnumProc)){
//nEnumProc /= sizeof(DWORD);
for (size_t i = 0; i < nEnumProc; ++i) {
MaxCount++;
//PROCESS_ALL_ACCESS
Profile *Pro=ServerProfiles.GetByID((int)a_dwProcIds);
HANDLE Process;
if (Pro && Pro->hID){
Process=Pro->hProcess;
Process=0;
}
else
Process=OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
a_dwProcIds[i]);

//HANDLE Process = (HANDLE)a_dwProcIds[i];
if (GetProcessTimes(Process, &Enter, &Exit, &KernalTime,
&UserTime)){
//Msg("Unable to get idle time", 0, 0);

memcpy(&Kernal, &KernalTime, sizeof(FILETIME));
memcpy(&User, &UserTime, sizeof(FILETIME));
//Get a running total of the process times

sumKernal.QuadPart+=Kernal.QuadPart;
sumUser.QuadPart+=sumUser.QuadPart;

ProcCount++;
CloseHandle(Process);
}
}

if (!Once++){
lastKernal.QuadPart=sumKernal.QuadPart;
lastUser.QuadPart=sumUser.QuadPart;
}

}

//LARGE_INTEGER Total=lastKernal+lastUser;
float CurrentAmount=(float)((sumKernal.QuadPart+sumUser.QuadPart) -
(lastKernal.QuadPart+lastUser.QuadPart)) / (float)100000;
//sprintf(buffer, "Processor Usage (%0.2f) from %d/%d", CurrentAmount,
ProcCount, MaxCount);
//Msg(buffer, 0, 0);
if (CurrentAmount < 0)
CurrentAmount=0;
if (CurrentAmount > 100)
CurrentAmount=100;
lastKernal.QuadPart=sumKernal.QuadPart;
lastUser.QuadPart=sumUser.QuadPart;
return CurrentAmount;

}

0 mensajes nuevos