Reputation: 578
I've researched a lot but all I can find is how to get the a single process time.
Process p = exampleProcess
return p.TotalProcessorTime
How can I get the total processor time? Will I get the % CPU usage of that process if I perform:
return p/totalProcessorTime
?
Upvotes: 1
Views: 8078
Reputation: 941218
Nah, you can't divide a Process
by a Timespan
. TotalProcessorTime
is a measurement of how much time was actually spent executing code. It is an absolute number. If you want a relative number then you need to measure how long the process has been running. Subtract StartTime
from ExitTime
. Like this:
Process prc = /* something */
var wallTime = DateTime.Now - prc.StartTime;
if (prc.HasExited) wallTime = prc.ExitTime - prc.StartTime;
var procTime = prc.TotalProcessorTime;
var cpuUsage = 100 * procTime.TotalMilliseconds / wallTime.TotalMilliseconds;
Upvotes: 2
Reputation: 99957
You can use PerformanceCounter
:
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
double currentCpuPercent = cpuCounter.NextValue();
Upvotes: 2
Reputation: 27864
You want the total processor time, not limited to a single process, correct? Does that mean you want the processor time for all processes on the system? Wouldn't that be the same as the elapsed wall time since the system was started? If so, GetTickCount64 will do the trick.
Upvotes: 0