2

I'm trying to get the CPU usage of a specific process, but it returns just 0. I still don't know what the problem is.

Process[] processlist = Process.GetProcesses(); foreach (Process theprocess in processlist) { if (GetProcessOwner(theprocess.Id) != "NO_OWNER") { if (theprocess.ProcessName != "svchost") { var ram = BytesToString(theprocess.PeakWorkingSet64); ram = ram.Replace("MB", ""); string state = ""; if (theprocess.MainWindowTitle == "") { state = "background"; } else { state = "foreground"; } sw.WriteLine("ID=" + theprocess.Id + "&NAME=" + theprocess.ProcessName + "&RAM=" + ram + "&STARTED=" + theprocess.StartTime + "&STATE=" + state); PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName); Console.WriteLine("CPU="+counter.NextValue()); } } } 
3
  • Just wondering did you create an object for p.ProcessName. I tried to copy and past it but it isn't defined. Commented Jan 18, 2014 at 16:58
  • The first call to NextValue() initializes the counter. Then you call it repeatedly afterwards, one second apart, and you get the usage during that last second. Having to wait that second is important, you use a timer. Commented Jan 18, 2014 at 18:53
  • Possible duplicate Why the cpu performance counter kept reporting 0% cpu usage? Commented Jan 18, 2014 at 18:57

1 Answer 1

1

It's okay, because NextValue always return 0 when you call it first time.

For fix this error you can call NextValue function twice after creation PerformanceCounter object (durty hack).

Sign up to request clarification or add additional context in comments.

4 Comments

>If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read. msdn.microsoft.com/en-us/library/…
So it's impossible to get the CPU percentage of all processes within 1 minute?
it's possible by dividing collection information on two stages: first loop is for creation PerformanceCounter objects and first call of NextValue function, second is for second call of NextValue . two stages must be devided by Thread.sleep
^Can you add this clarification to your answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.