Skip to content

Instantly share code, notes, and snippets.

@EricSch
Created September 19, 2008 20:59
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 EricSch/11658 to your computer and use it in GitHub Desktop.
Save EricSch/11658 to your computer and use it in GitHub Desktop.
namespace CpuUsage
{
using System;
using System.Diagnostics;
public class CpuMeter : IDisposable
{
private CounterSample _startSample;
private readonly PerformanceCounter _cnt;
/// Creates a per-process CPU meter instance tied to the current process.
public CpuMeter()
{
String instancename = GetCurrentProcessInstanceName();
_cnt = new PerformanceCounter("Process", "% Processor Time", instancename, true);
ResetCounter();
}
/// Creates a per-process CPU meter instance tied to a specific process.
public CpuMeter(int pid)
{
String instancename = GetProcessInstanceName(pid);
_cnt = new PerformanceCounter("Process", "% Processor Time", instancename, true);
ResetCounter();
}
/// Resets the internal counter. All subsequent calls to GetCpuUtilization() will
/// be relative to the point in time when you called ResetCounter(). This
/// method can be call as often as necessary to get a new baseline for
/// CPU utilization measurements.
public void ResetCounter()
{
_startSample = _cnt.NextSample();
}
/// Returns this process's CPU utilization since the last call to ResetCounter().
public double GetCpuUtilization()
{
CounterSample curr = _cnt.NextSample();
double diffValue = curr.RawValue - _startSample.RawValue;
double diffTimestamp = curr.TimeStamp100nSec - _startSample.TimeStamp100nSec;
double usage = (diffValue/diffTimestamp)*100;
return usage;
}
private static string GetCurrentProcessInstanceName()
{
Process proc = Process.GetCurrentProcess();
int pid = proc.Id;
return GetProcessInstanceName(pid);
}
private static string GetProcessInstanceName(int pid)
{
var cat = new PerformanceCounterCategory("Process");
string[] instances = cat.GetInstanceNames();
foreach (string instance in instances)
{
using (var cnt = new PerformanceCounter("Process",
"ID Process", instance, true))
{
var val = (int) cnt.RawValue;
if (val == pid)
{
return instance;
}
}
}
throw new Exception("Could not find performance counter " +
"instance name for current process. This is truly strange ...");
}
public void Dispose()
{
if (_cnt != null) _cnt.Dispose();
}
}
}
namespace CpuUsage
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal class Program
{
private static void Main(string[] args)
{
var mtr = new CpuMeter();
// do some heavy stuff
double result = 0;
for (int i = 0; i < 100000000; i++)
{
result = result + Math.Sin(i);
}
double usage = mtr.GetCpuUtilization();
Console.WriteLine("Done. CPU Usage {0:#00.00} %", usage);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment