Skip to content

Instantly share code, notes, and snippets.

@suntong
Created July 31, 2018 18:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suntong/647cfc96711e9305d391cb0f587409fc to your computer and use it in GitHub Desktop.
Save suntong/647cfc96711e9305d391cb0f587409fc to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
namespace PerformanceCounterTest
{
public class Program
{
public static void Main(string[] args)
{
TestA();
TestByID();
TestB1(20);
//TestB2(10);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static void TestA()
{
// https://stackoverflow.com/questions/3411805/
// https://stackoverflow.com/questions/8972239/
Console.WriteLine("## TestA");
Process process = Process.GetCurrentProcess();
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
// prevent process always be 0 value for processor %
cpuCounter.NextValue();
for (int i = 1; i <= 20; i++)
{
double ram = ramCounter.NextValue();
double cpu = cpuCounter.NextValue();
Console.WriteLine($@"[{i}] RAM: " + (ram / 1024 / 1024) + " MB; CPU: " + (cpu) + " %");
Thread.Sleep(300); DoSomething();
}
}
static void TestByID()
{
Console.WriteLine("## TestByID");
Process process = Process.GetCurrentProcess();
// http://dotnetdust.blogspot.com/2011/02/getting-processor-time-for-process-by.html
PerformanceCounter pc = new PerformanceCounter("Process", "% Processor Time", GetPerformanceCounterProcessName(process.Id), true);
pc.NextValue();
for (int i = 1; i <= 20; i++)
{
float cpuPercent = pc.NextValue() / Environment.ProcessorCount;
Console.WriteLine($@"CPU: {cpuPercent} %");
Thread.Sleep(300); DoSomething();
}
//Console.WriteLine("Press any key ...");
//Console.ReadKey();
}
private static string GetPerformanceCounterProcessName(int pid)
{
return GetPerformanceCounterProcessName(pid, System.Diagnostics.Process.GetProcessById(pid).ProcessName);
}
private static string GetPerformanceCounterProcessName(int pid, string processName)
{
int nameIndex = 0;
string value = processName;
string counterName = processName;
PerformanceCounter pc = new PerformanceCounter("Process", "ID Process", counterName, true);
while (true)
{
try
{
if (pid == (int)pc.NextValue())
{
value = counterName;
break;
}
else
{
nameIndex++;
counterName = processName + "#" + nameIndex;
pc = new PerformanceCounter("Process", "ID Process", counterName, true);
}
}
catch (SystemException ex)
{
if (ex.Message == "Instance '" + counterName + "' does not exist in the specified Category.")
{
break;
}
else
{
throw;
}
}
}
return value;
}
static void TestB1(int max)
{
Console.WriteLine("## TestB1");
var perfCounter = new PerformanceCounter("Process", "% Processor Time", "chrome");
// Initialize to start capturing
perfCounter.NextValue();
for (int i = 1; i <= max; i++)
{
// give some time to accumulate data
Thread.Sleep(1000);
float cpu = perfCounter.NextValue() / Environment.ProcessorCount;
Console.WriteLine("Chrome CPU: " + cpu);
}
//Console.WriteLine("Press any key ...");
//Console.ReadKey();
}
static void TestB2(int max)
{
Console.WriteLine("## TestB2");
// grab all Chrome process instances
var processes = Process.GetProcessesByName("chrome");
for (int i = 0; i < max; i++)
{
foreach (var p in processes)
{
var counter = ProcessCpuCounter.GetPerfCounterForProcessId(p.Id);
// start capturing
counter.NextValue();
Thread.Sleep(200);
float cpu = counter.NextValue() / (float)Environment.ProcessorCount;
Console.WriteLine(counter.InstanceName + " - Cpu: " + cpu);
}
}
//Console.WriteLine("Press any key ...");
//Console.ReadKey();
}
static void DoSomething()
{
Random r = new Random();
int s = 0;
for (int i = 1; i <= 2000; i++)
{
s += r.Next(1, 10);
}
}
}
public class ProcessCpuCounter
{
// https://weblog.west-wind.com/posts/2014/Sep/27/Capturing-Performance-Counter-Data-for-a-Process-by-Process-Id
public static PerformanceCounter GetPerfCounterForProcessId(int processId, string processCounterName = "% Processor Time")
{
string instance = GetInstanceNameForProcessId(processId);
if (string.IsNullOrEmpty(instance))
return null;
return new PerformanceCounter("Process", processCounterName, instance);
}
public static string GetInstanceNameForProcessId(int processId)
{
var process = Process.GetProcessById(processId);
string processName = Path.GetFileNameWithoutExtension(process.ProcessName);
PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");
string[] instances = cat.GetInstanceNames()
.Where(inst => inst.StartsWith(processName))
.ToArray();
foreach (string instance in instances)
{
using (PerformanceCounter cnt = new PerformanceCounter("Process",
"ID Process", instance, true))
{
int val = (int)cnt.RawValue;
if (val == processId)
{
return instance;
}
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment