Get Usage of RAM, Hark disk space, CPU usage accurately using C# - c#

I'm trying to implement a program which can monitor the System usage statistics and report/alert when the usage (Configured in the program config. settings) go beyond the provided limit.
I tried PerformanceCounter and ManagementObjectSearcher to fetch and compare with Task Manager CPU usage but not getting the values even close to the taskmanager values.
Currently, I am following this link Link
Source Code
class Program
{
static List<float> AvailableCPU = new List<float>();
static List<float> AvailableRAM = new List<float>();
protected static PerformanceCounter cpuCounter;
protected static PerformanceCounter ramCounter;
static List<PerformanceCounter> cpuCounters = new List<PerformanceCounter>();
static int cores = 0;
static void Main(string[] args)
{
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
cores = cores + int.Parse(item["NumberOfCores"].ToString());
}
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
int procCount = System.Environment.ProcessorCount;
for (int i = 0; i < procCount; i++)
{
System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", i.ToString());
cpuCounters.Add(pc);
}
Thread c = new Thread(ConsumeCPU);
c.IsBackground = true;
c.Start();
try
{
System.Timers.Timer t = new System.Timers.Timer(1200);
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
Thread.Sleep(10000);
}
catch (Exception e)
{
Console.WriteLine("catched exception");
}
Console.ReadLine();
}
public static void ConsumeCPU()
{
int percentage = 60;
if (percentage < 0 || percentage > 100)
throw new ArgumentException("percentage");
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
// Make the loop go on for "percentage" milliseconds then sleep the
// remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms
if (watch.ElapsedMilliseconds > percentage)
{
Thread.Sleep(100 - percentage);
watch.Reset();
watch.Start();
}
}
}
public static void TimerElapsed(object source, ElapsedEventArgs e)
{
float cpu = cpuCounter.NextValue();
float sum = 0;
foreach (PerformanceCounter c in cpuCounters)
{
sum = sum + c.NextValue();
}
sum = sum / (cores);
float ram = ramCounter.NextValue();
Console.WriteLine(string.Format("CPU Value 1: {0}, cpu value 2: {1} ,ram value: {2}", sum, cpu, ram));
AvailableCPU.Add(sum);
AvailableRAM.Add(ram);
}
}
At times it goes beyond 100%. Please suggest some method which can help me fetch the CPU usage somewhere close to the TaskManager values.

Related

Get the realtime CPU speed in C#?

The existing question suggests CurrentClockSpeed, but in my system, it just returns the same value as MaxClockSpeed. The code below prints out the same two values over and over again.
Task.Run(() =>
{
ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
while (true)
{
Debug.WriteLine("Max=" + Mo["MaxClockSpeed"] + ", Current=" + Mo["CurrentClockSpeed"]);
System.Threading.Thread.Sleep(1000);
}
Mo.Dispose(); //return and such later in the code
});
But all other applications like Task Manager, CPU-Z, Hardware Info, etc, show variable clock speed. That is, if I run a process that uses 100% of the CPU, the speed goes up, and if I terminate that process, it goes down. How can I get THAT value?
I mean, for example, the value in the "Speed" section of the screenshot I found in Google Search. Not the "Maximum speed" value that never changes.
If you mean CPU current usage processes
use this function in seperate thread :
private void get_cpuUsage()
{
try
{
string processname = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var perfCounter = new PerformanceCounter("Process", "% Processor Time", processname);
int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
coreCount += int.Parse(item["NumberOfCores"].ToString());
}
while (true)
{
Thread.Sleep(500);
double perfVal = perfCounter.NextValue() / Environment.ProcessorCount;
int cpu = (int)Math.Round(perfVal, 0);// /
double cpuvalue = Math.Round(perfVal, 1);
Invoke((MethodInvoker)delegate
{
cpu_bar.Text = cpuvalue.ToString(); // diaplay current % processes
});
}
}
catch(Exception ex)
{
messagebox.show(ex.message);
}
}

Multithreading is taking more time than sequential threading

I am new to C#
I am generating random numbers saving into an integer array of size 1 million, then I search user input number and its occurrences in an array using single thread then I search it using 5 threads. My processor has 4 cores.
THE PROBLEM is multithreading is taking way more time than sequential I just cannot figure out why any help would be much appreciated.
Here is the code.
namespace LAB_2
{
class Program
{
static int[] arr = new int[1000000];
static int counter = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0,c5=0;
static int x = 0;
#if DEBUG
static void Main(string[] args)
{
try
{
//Take input
generate();
Console.WriteLine("Enter number to search for its occurances");
x = Console.Read();
//Multithreaded search
Stopwatch stopwatch2 = Stopwatch.StartNew();
multithreaded_search();
stopwatch2.Stop();
Console.WriteLine("Multithreaded search");
Console.WriteLine("Total milliseconds with multiple threads = " + stopwatch2.ElapsedMilliseconds);
//search without multithreading
Stopwatch stopwatch = Stopwatch.StartNew();
search();
stopwatch.Stop();
Console.WriteLine("Total milliseconds without multiple threads = " + stopwatch.ElapsedMilliseconds);
}
finally
{
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
#endif
}
public static void generate() //Populate the array
{
Random rnd = new Random();
for (int i = 0; i < 1000000; i++)
{
arr[i] = rnd.Next(1, 500000);
}
}
public static void search() //single threaded/Normal searching
{
int counter = 0;
for (int i = 0; i < 1000000; i++)
{
if (x == arr[i])
{
counter++;
}
}
Console.WriteLine("Number of occurances " + counter);
}
public static void multithreaded_search()
{
Task thr1 = Task.Factory.StartNew(() => doStuff(0, 200000, "c1"));
Task thr2 = Task.Factory.StartNew(() => doStuff(200001, 400000, "c2"));
Task thr3 = Task.Factory.StartNew(() => doStuff(400001, 600000, "c3"));
Task thr4 = Task.Factory.StartNew(() => doStuff(600001, 800000, "c4"));
Task thr5 = Task.Factory.StartNew(() => doStuff(800001, 1000000, "c5"));
//IF I don't use WaitAll then the search is
//faster than sequential, but gets compromised
Task.WaitAll(thr1, thr2, thr3, thr4, thr5);
counter = c1 + c2 + c3 + c4 + c5;
Console.WriteLine("Multithreaded search");
Console.WriteLine("Number of occurances " + counter);
}
static void doStuff(int stime, int etime, String c)
{
for (int i = stime; i < etime; i++)
{
if (x == arr[i])
{
switch (c)
{
case "c1":
c1++;
break;
case "c2":
c2++;
break;
case "c3":
c3++;
break;
case "c4":
c4++;
break;
case "c5":
c5++;
break;
};
}
Thread.Yield();
}
}
}
}
First, in your doStuff you do more work than in search. While it is not likely to have a tangible effect, you never know.
Second, Thread.Yield is a killer with tasks. This methods is intended to be used in very marginal situations like spinning when you think a lock might be too expensive. Here, it is just a brake to your code, causing the OS scheduler to do more work, perhaps even do a context-switch on the current core, which in turn will invalidate the cache.
Finally, your data and computations are small. Moderns CPUs will enumerate such an array in no time, and it is likely a great part of it, or even all, fits in the cache. Concurrent processing has its overhead.
I recommend Benchmark.NET.

Comparison time- Single Threads vs Multiple Threads differing in results

I wrote this code in purpose to test multi and single threading speeds. Thanks for all the feedback! I rewrote most of it based on the great comments I received. This now functions properly (maybe has a bug here or there), tests multi threads first, and takes an average to find a more accurate speed: (Scroll to bottom for cont.)
Main method Class
using System;
namespace SingleAndMultiThreading
{
internal class Threads
{
private static void Main(string[] args)
{
long numOfObjCreated;
int numberOfTests;
while (true)
{
try
{
Console.Write("Number of objects to create: ");
numOfObjCreated = Convert.ToInt64(Console.ReadLine());
break;
}
catch (Exception)
{
Console.WriteLine("Invalid input.");
}
}
while (true)
{
try
{
Console.Write("Number of tests to run: ");
numberOfTests = Convert.ToInt32(Console.ReadLine());
break;
}
catch (Exception)
{
Console.WriteLine("Invalid input.");
}
}
CalculateResults(numOfObjCreated, numberOfTests);
Console.ReadKey();
}
private static void CalculateResults(long numOfObjCreated, int numberOfTests)
{
double totalPercentages = 0;
for (var i = 0; i < numberOfTests; i++)
{
totalPercentages += CompleteTests(numOfObjCreated);
}
var accuracy = totalPercentages / numberOfTests;
if ((int)accuracy == 0)
{
Console.WriteLine("\nIn this case, neither single threading or multithreading is faster.\n" +
"They both run equally well under these conditions.\n");
return;
}
if (accuracy < 0)
{
Console.WriteLine("\nIn this case with {0} objects being created, single threading is faster!\n",
string.Format("{0:#,###0}", numOfObjCreated));
return;
}
Console.WriteLine("\nFrom {0} test(s), {1}% was the average percentage of increased speed in multithreading.\n",
string.Format("{0:#,###0}", numberOfTests), string.Format("{0:#,###0}", accuracy));
}
private static double CompleteTests(long numOfObjCreated)
{
Console.WriteLine("Computing...");
var numOfCores = Environment.ProcessorCount;
var timeForMultiThread = MultiThread.Run(numOfObjCreated, numOfCores);
var timeForSingleThread = SingleThread.Run(numOfObjCreated);
var percentFaster = ((timeForSingleThread / timeForMultiThread) * 100) - 100;
//note: .NET does its part in assigning a certian thread to its own core
Console.WriteLine("Using all {0} cores, creating {1} objects is {2}% faster.",
numOfCores, string.Format("{0:#,###0}", numOfObjCreated), string.Format("{0:#,###0}", percentFaster));
return percentFaster;
}
}
}
Single Threading Class
using System;
using System.Diagnostics;
namespace SingleAndMultiThreading
{
internal class SingleThread
{
public static double Run(long numOfObjCreated)
{
var watch = new Stopwatch();
watch.Start();
for (long i = 0; i < numOfObjCreated; i++)
{
new object();
}
watch.Stop();
var totalTime = watch.ElapsedTicks;
Console.WriteLine("The time to create {0} objects with 1 thread is: {1} ticks.",
string.Format("{0:#,###0}", numOfObjCreated), string.Format("{0:#,###0}", totalTime));
return totalTime;
}
}
}
Multi Threading Class
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace SingleAndMultiThreading
{
internal class MultiThread
{
public static double Run(long numOfObjCreated, int numOfCores)
{
var watch = new Stopwatch();
var workerObject = new Worker(numOfObjCreated / numOfCores);
var listOfThreads = new List<Thread>();
for (long k = 0; k < numOfCores; k++)
{
var workerThread = new Thread(workerObject.DoWork);
listOfThreads.Add(workerThread);
}
watch.Start();
foreach (var thread in listOfThreads)
{
thread.Start();
}
byte countOfCompletedThreads = 0;
while (true)
{
foreach (var thread in listOfThreads)
if (!thread.IsAlive)
countOfCompletedThreads++;
if (countOfCompletedThreads == numOfCores)
break;
countOfCompletedThreads = 0;
}
watch.Stop();
var totalTime = watch.ElapsedTicks;
Console.WriteLine("The time to create {0} objects utilizing all {1} cores is: {2} ticks.",
string.Format("{0:#,###0}", numOfObjCreated), numOfCores, string.Format("{0:#,###0}", totalTime));
return totalTime;
}
}
}
Worker Class
namespace SingleAndMultiThreading
{
public class Worker
{
private readonly long _numOfObjToCreate;
public bool IsDone;
public Worker(long numOfObjToCreate)
{
_numOfObjToCreate = numOfObjToCreate;
}
public void DoWork()
{
for (long i = 0; i < _numOfObjToCreate; i++)
{
new object();
}
IsDone = true;
}
}
}
The output of this code is a bit too long to post (I urge you to copy and paste into your own IDE, its really fascinating). I guess the accepted answer that this doesn't give the same result per every test is due to CPU scheduling, other or minor issues like ASLR and such. More than one thing is happening aside from visual studio running this program, and priorities differently. Also thank you for pointing out that running multi threading first helps because of the already-done memory allocation!
Another thing to point out, I found this while running:
The spikes are when the process of multi threading takes place.

CPU usage is much higher when multithreaded program is run from visual studio

I found this really strange. I was testing a program that create 1500 thread concurrently. When I run this program from visual studio 2013, cpu usage goes higher (around 60%) but when i run the exe, cpu usage remains below 10%.
static ManualResetEvent _doneEvent = new ManualResetEvent(false);
private static int _numerOfThreadsNotYetCompleted = 1500;
private static readonly object ob= new object();
static void Main(string[] args)
{
List<System.Threading.Tasks.Task> taskList = new List<System.Threading.Tasks.Task>();
Console.Read();
for (int i = 0; i <= 1500; ++i)
{
var j = i;
var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
Thread obj = new Thread(() =>
{
Thread.Sleep(10000);
lock (ob)
{
Console.WriteLine(_numerOfThreadsNotYetCompleted);
if (Interlocked.Decrement(ref _numerOfThreadsNotYetCompleted) == 0)
_doneEvent.Set();
}
});
obj.Start();
}
_doneEvent.WaitOne();
Console.WriteLine("All done.");
}
Thanks In Advance

Assign threads to task in C#

I have multiple tasks in an array, that are used to compute prime numbers in a given range. To undergo a comparison of tasks vs thread performance, I want to use threads within tasks and then check the performance stats.
How will the threads be used with tasks, so far this is what I have done:
public Form1()
{
InitializeComponent();
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
this.scheduler = TaskScheduler.FromCurrentSynchronizationContext();
this.numericUpDown1.Maximum = int.MaxValue;
}
private void btnCalculate_Click(object sender, EventArgs e)
{
//get the lower and upper bounds for prime range
int lower = int.Parse(this.numericUpDown1.Value.ToString());
int upper = 0 ;
//get the time in milliseconds for task deadline
int taskDeadline = int.Parse(this.time.Text);
//determine tasks completed
int tasksCompleted = 0;
Random random = new Random();
for (int taskCount = 1; taskCount <= 1; ++taskCount)
{
int taskArraySize = taskCount * 100;
Task[] taskArray = new Task[taskArraySize];
this.txtNumOfPrimes.Text += "Performing test for " +
taskArraySize.ToString() +
" tasks" +
Environment.NewLine +
Environment.NewLine;
for (int i = 0; i < taskArray.Length; i++)
{
upper = random.Next(5, 10);
taskArray[i] = new Task(() => getPrimesInRange(lower, upper));
taskArray[i].Start();
bool timeout = taskArray[i].Wait(taskDeadline);
if (!timeout)
{
// If it hasn't finished at timeout display message
this.txtNumOfPrimes.Text +=
"Message to User: Task not completed, Status=> " +
taskArray[i].Status.ToString() +
Environment.NewLine;
}
else
{
this.txtNumOfPrimes.Text += "Task completed in timeout " +
", CPU usage: " + this.getCurrentCpuUsage() +
", RAM usage: " +
this.getAvailableRAM() +
Environment.NewLine;
tasksCompleted++;
}
}
}
this.txtNumOfPrimes.Text += Environment.NewLine;
this.txtNumOfPrimes.Text +=
"Tasks Completed: " +
tasksCompleted.ToString() +
Environment.NewLine;
}
The whole point of tasks is "simplifying the process of adding parallelism and concurrency to applications". Indeed (from http://msdn.microsoft.com/en-us/library/dd537609):
Behind the scenes, tasks are queued to the ThreadPool, which has been
enhanced with algorithms (like hill-climbing) that determine and
adjust to the number of threads that maximizes throughput. This makes
tasks relatively lightweight, and you can create many of them to
enable fine-grained parallelism. To complement this, widely-known
work-stealing algorithms are employed to provide load-balancing.
In short, tasks do the thread work without much of the hassle and legwork.
To compare the two, consider using Parrallel.ForEach for tasks. For example:
public class PrimeRange
{
public int Start;
public int Snd;
}
List<PrimeRange> primes = new []
{
new PrimeRange{Start = 0, End = 1000},
new PrimeRange{Start = 1001, End = 2000}
// An so on
};
Parallel.ForEach(primes, x => CalculatePrimes(x, OnResult())));
where CalculatePrimes is a method that takes a PrimeRange and a delegate to call when the primes have been calculated. Parraler.ForEach will start a task for each element of primes and run CalculatePrimes() on it and handle the thread assignment and scheduling for you.
To compare it to threads, use something like:
List<Thread> threads = new List<Thread>();
foreach(PrimeRange primeRange in primes)
{
threads = new Thread(CalculatePrimes).Start(x);
}
foreach(var thread in threads)
{
thread.Join();
}
where CalculatePrimes would need to also store the results (or something similar). See C# Waiting for multiple threads to finish for more information about waiting on running threads.
You could time the results using a StopWatch.

Categories

Resources