public
Last active

  • Download Gist
CpuMeter.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
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();
}
}
}
Program.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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();
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.