Unity C# System Diagnostics PerformanceCounter CPU RAM - c#

Looking to get the CPU/RAM %, I implemented the code below, however the counters always return CPU 100, RAM 0. I've tried 2sec invokes, same result. Googling this issue results in a thousand responses saying it's caused by no delay (which it usually is in the code samples seen), however given the invokes I've used, doesn't seem to be the cause here?
public class ScriptName : MonoBehaviour
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
void Start()
{
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
cpuCounter.NextValue();
ramCounter.NextValue();
Invoke("UpdatePerformance", 1);
}
public void UpdatePerformance()
{
float cpu = cpuCounter.NextValue(); // Ouputs 100
float ram = ramCounter.NextValue(); // Outputs 0
Invoke("UpdatePerformance", 1); // 2 sec delay, same output
}
}
Thanks

Related

How to get cpu utilization data for phantomJS browser?

public static readonly PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
public static readonly PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
public static readonly PerformanceCounter theCPUCounterPhantomJS =
new PerformanceCounter("Processor", "% Processor Time", Process.GetProcessesByName("phantomjs").ToString());
public static void getCurrentCpuUsage()
{
Console.WriteLine(theCPUCounter.NextValue() + " %");
}
public static void getAvailableRAM()
{
Console.WriteLine(theMemCounter.NextValue() + " MB");
}
public static void getCurrentCpuUsagePhantomJS()
{
Console.WriteLine(theCPUCounterPhantomJS.NextValue() + " %");
}
I want cpu utilization data for PhantomJS browser. Here is the code that I am using. I just want to know that what parameter I can enter instead of Process.GetProcessesByName("phantomjs").ToString(). I tried many approach but it fails and gave me exception System.InvalidOperationException : Instance 'System.Diagnostics.Process[]' does not exist in the specified Category. .The name of the process is phantomjs.exe that shows in task manager. Please advice.
See the docs - this is how you should instantiate the performance counter in your case:
new PerformanceCounter(
"Process",
"% Processor Time",
"phantomjs");
Process.GetProcessesByName returns an array of processes, and so the ToString results in "System.Diagnostics.Process[]", which is not a valid instance name, not under the Processor category, and not under the Process category.

get current cpu usage using c# in asp.net framework

I would like to find out the current CPU usage using the codes below(c# in asp.net framework). However it gives me "0% of CPU usage" when I try to run the program. When I check my task manager, I found out that the actual total CPU usage is more than 5%. Does anyone know what is wrong with the code below?
public partial class cpuUsage : System.Web.UI.Page
{
PerformanceCounter cpu;
protected void Page_Load(object sender, EventArgs e)
{
cpu = new PerformanceCounter();
cpu.CategoryName = "Processor";
cpu.CounterName = "% Processor Time";
cpu.InstanceName = "_Total";
lblCPUUsage.Text = getCurrentCpuUsage();
}
public string getCurrentCpuUsage()
{
return cpu.NextValue() + "%";
}
}
The first value returned by a PerformanceCounter will always be 0. You'll need a Timer or Thread that keeps monitoring the value in the background. This code for example will output the correct value every second (don't use this actual code, it's quick and dirty):
new Thread(() =>
{
var cpu = new PerformanceCounter
{
CategoryName = "Processor",
CounterName = "% Processor Time",
InstanceName = "_Total"
}
while (true)
{
Debug.WriteLine("{0:0.0}%", cpu.NextValue());
Thread.Sleep(1000);
}
}).Start();
Make sure to read the remarks of the PerformanceCounter.NextValue method:
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.

C# - Performance Counter lower than Taskmanager % [duplicate]

This question already has answers here:
PerformanceCounter reporting higher CPU usage than what's observed
(2 answers)
Closed 2 years ago.
I try to make a class which will fetch different usages from the pc, the problem that I have atm is that the CPU usage is under what Task Manager displays (with about 10%).
Can you please have a look and point me in the right direction ? Please no answers without explanation, I want to learn !
Here is what I have atm :
using System.Diagnostics;
using System.Net.NetworkInformation;
namespace ConsoleApplication2
{
class UsageFetcher
{
ulong totalRAM;
PerformanceCounter cpuUsage;
PerformanceCounter ramUsage;
PerformanceCounter diskUsage;
NetworkInterface[] networkUsage;
public UsageFetcher()
{
// Fetching total amount of RAM to be able to determine used persantage
//totalRAM = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
totalRAM = this.getTotalRam();
// Creating a new Perfromance Counter who will be used to get the CPU Usage
cpuUsage = new PerformanceCounter();
// Setting it up to fetch CPU Usage
cpuUsage.CategoryName = "Processor";
cpuUsage.CounterName = "% Processor Time";
cpuUsage.InstanceName = "_Total";
/*
* Fetching the first two reads
* First read is always 0 so we must elimiate it
*/
cpuUsage.NextValue();
cpuUsage.NextValue();
// Creating a new Performance Counter who will be used to get the Memory Usage
ramUsage = new PerformanceCounter();
// Setting it up to fetch Memory Usage
ramUsage.CategoryName = "Memory";
ramUsage.CounterName = "Available Bytes";
// Fetching the first two reads !! Same reason as above !!
ramUsage.NextValue();
ramUsage.NextValue();
}
public string getCPUUsage()
{
/*
* Requesting the usage of the CPU
* It is returned as a float thus I need to call ToString()
*/
return cpuUsage.NextValue().ToString();
}
public string getMemUsage()
{
// Requesting memory usage and calculate how much is free
return (100 -ramUsage.NextValue() / totalRAM * 100).ToString();
}
public ulong getTotalRam()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory ;
}
}
}
According to this SO post here: Why the cpu performance counter kept reporting 0% cpu usage?
You need to sleep for at least a second for the NextValue() method to return a decent result.
Try adding a call to Sleep between your calls to NextValue and see what you get.

Performance counter C# and HyperPi

I am in attempt to get CPU Usage reading correctly. The code below is executed without problem but I can't get CPU Usage reading at 100% when I run Hyper PI which is a multicores CPU stress test. What did I do wrong? Thank you for your time.
Alternatively, is it possible to get CPU Usage readings from WMI?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace TestHarnessCPUUsage
{
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
ramCounter.CategoryName = "Memory";
ramCounter.CounterName = "Available MBytes";
Console.WriteLine(cpuCounter.NextValue()
+ "%");
Console.WriteLine(ramCounter.NextValue()
+ "MB");
Console.ReadKey();
}
}
}
That's the kind of perf counter you have to sample yourself. Processor time is a measure over an interval. It tells you how long the processor was turned off, versus it running at 100%. The ratio is the value you get, times 100. One second is the typical interval time, like TaskMgr.exe and Perfmon uses. The smaller you make the interval, the 'noisier' it gets. Down to one sample, like you did, where you get no data at all since there wasn't an interval. Fix:
using System;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
cpuCounter.NextValue();
while (!Console.KeyAvailable) {
System.Threading.Thread.Sleep(1000);
Console.WriteLine(cpuCounter.NextValue());
}
}
}

How do I get the CPU speed and total physical ram in C#?

I need a simple way of checking how much ram and fast the CPU of the host PC is. I tried WMI however the code I'm using
private long getCPU()
{
ManagementClass mObject = new ManagementClass("Win32_Processor");
mObject.Get();
return (long)mObject.Properties["MaxClockSpeed"].Value;
}
Throws a null reference exception. Furthermore, WMI queries are a bit slow and I need to make a few to get all the specs. Is there a better way?
http://dotnet-snippets.com/dns/get-the-cpu-speed-in-mhz-SID575.aspx
using System.Management;
public uint CPUSpeed()
{
ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
uint sp = (uint)(Mo["CurrentClockSpeed"]);
Mo.Dispose();
return sp;
}
RAM can be found in this SO question: How do you get total amount of RAM the computer has?
You should use PerformanceCounter class in System.Diagnostics
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
public string getCurrentCpuUsage(){
cpuCounter.NextValue()+"%";
}
public string getAvailableRAM(){
ramCounter.NextValue()+"MB";
}
Much about the processor including its speed in Mhz is available under HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor
I'm running 2 Win7x64 pcs and for some reason the WMI query shows a vague number the first time I run the code and the correct processor speed the second time I run it?
When it comes to performance counters, I did work a LOT with the network counters and got in accurate results and eventually had to find a better solution, so I dont trust them!

Categories