Skip to content

Instantly share code, notes, and snippets.

@PrashantUnity
Last active October 21, 2022 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PrashantUnity/ae69becb4b9442cb38cdbdc134c5f0fb to your computer and use it in GitHub Desktop.
Save PrashantUnity/ae69becb4b9442cb38cdbdc134c5f0fb to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace CpuUses
{
class Program
{
static PerformanceCounter cpuCounter;
static PerformanceCounter ramCounter;
static int interval =3000;
const string path = "YourPathOfTextFile";
static void Main()
{
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
GetCurrentCpuUsage();
GetAvailableRAM();
StoreInTextFile();
//PrintOnConsole();
}
public static void PrintOnConsole()
{
Console.WriteLine(string.Format("{0,6} {1,20:N0} {2,25:N0}", "Cpu Uses", "Available Ram", "Current DateTime"));
while (true)
{
Console.WriteLine(string.Format("{0,6} {1,20:N0} {2,30:N0}", GetCurrentCpuUsage(), GetAvailableRAM(), DateTime.Now.ToString()));
System.Threading.Thread.Sleep(interval);
}
}
public static void StoreInTextFile()
{
using (var sw = new StreamWriter(path))
{
sw.WriteLine(string.Format("{0,6} {1,20:N0} {2,25:N0}", "Cpu Uses", "Available Ram", "Current DateTime"));
}
while (true)
{
using (var sw = new StreamWriter(path, true))
{
sw.WriteLine(string.Format("{0,6} {1,20:N0} {2,30:N0}", GetCurrentCpuUsage(), GetAvailableRAM(), DateTime.Now.ToString()));
}
System.Threading.Thread.Sleep(interval);
}
}
public static string GetCurrentCpuUsage()
{
return (int)cpuCounter.NextValue() + "%";
}
public static string GetAvailableRAM()
{
return (int)ramCounter.NextValue() + "MB";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment