Sign in to follow this  

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

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;
using System.Threading;

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");
			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 this post

Link to post
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...

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this