# [C#] System.Diagnostics.PerformanceCounter NextValue() returns strange values

This topic is 3405 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey all, Finally decided to learn some C# this summer by trying to write a rather non-trivial program. Part of it requires me finding the CPU, RAM, and Network usage of the computer the application is running on. All sources seemed to point to System.Diagnostics.PerformanceCounter being the best method. I whipped up some test code to see if it would give the results I wanted. I am running Mono 2.4 on Mac OS X 10.5.7. Mono claims that PerformanceCounter was implemented in 2.0, so I shouldn't be having the problems I am. Here is the code:
using System;
using System.Diagnostics;

namespace performanceCounter
{
class MainClass
{
public static void Main(string[] args)
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
PerformanceCounter networkCounter;

cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

ramCounter = new PerformanceCounter("Memory", "Available MBytes");

networkCounter = new PerformanceCounter("Network Interface", "Bytes per Second");

cpuCounter.NextValue();
ramCounter.NextValue();
networkCounter.NextValue();

Console.WriteLine("Current CPU: {0}", cpuCounter.NextValue() +"%");
Console.WriteLine("RAM available: {0}", ramCounter.NextValue()+"MB");
Console.WriteLine("Network Usage: {0}", networkCounter.NextValue()+" Bytes/s");

}
}
}


I was told that since finding these metrics required some sort of difference, the first NextValue() would return 0. So I basically eat the first values and print the second. The results are as follow: Current CPU: 100% RAM available: 0MB Network Usage: 0 Bytes/s This seems a bit odd to me, so I threw a 5-second sleep in there for good measure between the first and second calls. Same output. So what am I doing wrong? Basically, my goal is to get, at any point in time, a good average of CPU and RAM usage, as well as network usage (for speed measurements -- though, I can get this other ways, so it is less important). Any ideas? Thanks!

##### Share on other sites
Okay, I assume the network code isn't working because I didn't provide an interface ... but using PerformanceCounterCategory to get the network interfaces, I get zilch for results.

Perhaps I should drop by the Mono boards, huh...

1. 1
2. 2
3. 3
4. 4
Rutin
12
5. 5

• 12
• 16
• 10
• 14
• 10
• ### Forum Statistics

• Total Topics
632659
• Total Posts
3007692
• ### Who's Online (See full list)

There are no registered users currently online

×