I want to get the performance data like in the performance tab in the task manager window.
I got this code:
using (PerformanceCounter pCounter = new PerformanceCounter())
{
pCounter.CategoryName = "Processor"; //this get me the cpu usage
pCounter.CounterName = "% Processor Time";
pCounter.InstanceName = "_Total";
// will always start at 0
pCounter.NextValue();
System.Threading.Thread.Sleep(1000);
//now matches task manager reading
float cpuUsage = pCounter.NextValue();
pCounter.CategoryName = "Memory";
pCounter.CounterName = "Available MBytes"; //this gets me the available memory
pCounter.InstanceName = string.Empty;
}
I also need:
The up time (time the server is active HH:mm:ss)
Number of processes
Number of threads
Ethernet usage
I have no idea how to get this data...
The .net framework provides the System.Diagnostics class with a plethora of methods to access system info including performance data.
https://msdn.microsoft.com/en-us/library/vstudio/System.Diagnostics%28v=vs.90%29.aspx
Related
I'm assuming I have found myself some sort of a nasty bug.
I have recently tried to create a console application in c# that prints the CPU Load & available memory every second. Whilst this goes on I have made sure that the application only warns about the CPU usage when the CPU Load goes over 80 percent. With a much more serious warning at 100% as you will see.
However, when i run the application it continually warns me that the CPU is at 100%, even though I know it shouldn't be running anywhere near that. I downloaded CPU Burn In to test the app and push the CPU to 100%, However I am 100 percent sure that it has been disabled the whole time.
I will post my code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.Speech.Synthesis;
namespace CpuandMemoryMonitor
{
class Program
{
/// <summary>
/// Entry Point into the Program | Program: CPU & Memory Monitor |By:
Andrew.
/// </summary>
///
static void Main(string[] args)
{
#region My performance Counters
// This will greet the user in the default voice
SpeechSynthesizer synth = new SpeechSynthesizer();
synth.Speak("Welcome to the CPU and Memory Monitor");
// This will pull the current CPU load in percentage.
PerformanceCounter perfCpuCount = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
// This will pull the current available Memory in Megabytes
PerformanceCounter perfMemCount = new PerformanceCounter("Memory", "Available MBytes");
// This will give us system uptime (in Seconds)
PerformanceCounter perfUptimecount = new PerformanceCounter("System", "System Up Time");
#endregion
#region Perfromance Counters Program Loop
//Infinite While Loop.
while (true)
{
// Get the current perforance counter values
int currentcpupercentage = (int)perfCpuCount.NextValue();
int currentavailablememory = (int)perfMemCount.NextValue();
//Print the performance counter values to the console screen
Console.WriteLine("CPU Load: {0}%", currentcpupercentage);
Console.WriteLine("Available Memory: {0}MB", currentavailablememory);
// Speech synthasiser warns user when CPU Load is above 80 percent
if (currentcpupercentage > 80)
{
///If CPU Load is at 100 % Warn the user in a a female voice!
if (currentcpupercentage == 100)
{
synth.SelectVoiceByHints(VoiceGender.Female);
string cpuLoadVocalMessage = String.Format("Oh dear! You're CPU is about to catch on Fire!");
synth.Speak(cpuLoadVocalMessage);
}
else
//If CPU Load is at 80 % Warn the user in a a male voice!
{
synth.SelectVoiceByHints(VoiceGender.Male);
string cpuLoadVocalMessage = String.Format("The Current Cpu Load is {0}", currentcpupercentage);
synth.Speak(cpuLoadVocalMessage);
}
// Speech synthasiser warns user when memory is less then 1 gigabyte
if (currentavailablememory < 1024)
{
// If CPU Load is at 100 % Warn the user ina a female voice!
string memavailableVocalMessage = string.Format("You currently have {0} gigabytes of memory available", currentavailablememory / 1024);
synth.Speak(memavailableVocalMessage);
}
//Sleep for 1 second
Thread.Sleep(1000);
}
#endregion
}
}
}
}
You have an infinite loop, if you have an infinite loop the computer will run the code continuously. As others have pointed out in the comments, you should use some form of timer in order to only poll at specific intervals. Even better you can use a WMI Event watcher to get called only when the alarm is hit.
Google WMI Events or read things like;
https://msdn.microsoft.com/en-us/library/aa393013(v=vs.85).aspx
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.
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.
I know that it's possible to get this information - Intel's own TurboBoost sidebar gadget appears to use an ActiveX control to determine the current clock speed of an i3/i5/i7 CPU when TurboBoost is active. However, I'm wanting to do this programmatically in C# - obtaining the CurrentClockSpeed value from WMI tops out at the set maximum clock speed of the CPU, so in TurboBoost mode, it doesn't report the current actual clock speed.
If you want to get the turbo speed, you can make use of the "% Processor Performance" performance counter and multiply it with the WMI "MaxClockSpeed" as follows:
private string GetCPUInfo()
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor Information", "% Processor Performance", "_Total");
double cpuValue = cpuCounter.NextValue();
Thread loop = new Thread(() => InfiniteLoop());
loop.Start();
Thread.Sleep(1000);
cpuValue = cpuCounter.NextValue();
loop.Abort();
foreach (ManagementObject obj in new ManagementObjectSearcher("SELECT *, Name FROM Win32_Processor").Get())
{
double maxSpeed = Convert.ToDouble(obj["MaxClockSpeed"]) / 1000;
double turboSpeed = maxSpeed * cpuValue / 100;
return string.Format("{0} Running at {1:0.00}Ghz, Turbo Speed: {2:0.00}Ghz", obj["Name"], maxSpeed, turboSpeed);
}
return string.Empty;
}
The InfiniteLoop method is simply an integer that gets 1 added and subtracted:
private void InfiniteLoop()
{
int i = 0;
while (true)
i = i + 1 - 1;
}
The InfiniteLoop method is just added to give the CPU something to do and turbo in the process. The loop is allowed to run for a second before the next value is taken and the loop aborted.
I also posted this answer on this question.
I do not believe it's possible to obtain this information with only safe/managed C# code, since WMI does not seem to supply this information. So i think you will need to use the CPUID instruction to get detailed information from the CPU that executes the instruction.
This documentation from Intel might help get you started:
http://www.intel.com/assets/pdf/appnote/241618.pdf
And here's some unsafe code to use with C#:
An attempt to bring CPUID to C#
Also see page 7 of:
Intel® Turbo Boost Technology in Intel® Core™ Microarchitecture (Nehalem) Based Processors
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!