Simplest Possible Performance Counter Example

Paul Matthews picture Paul Matthews · Oct 9, 2010 · Viewed 44.4k times · Source

What is the smallest amount of C# code to get a performance counter up and running?

I simply want to measure the number of CPU cycles and/or time between two points in my code. I've skimmed through all the waffle on the web but it seems like WAY more code than is necessary for such a trivial task. I just want to get a quick measurement up and running and concentrate more on what I'm working on.

Answer

driis picture driis · Oct 9, 2010

I don't think you need a performance counter for that. Do you need more than the timing you can get from StopWatch ? It is very accurate.

Stopwatch watch = Stopwatch.StartNew();

// Do work

watch.Stop();
// elapsed time is in watch.Elapsed

However, to answer the question you actually asked: If you just want to query existing counters, it is in fact quite simple. Here is a full example:

using System;
using System.Diagnostics;
using System.Linq;

static class Test
{
    static void Main()
    {
        var processorCategory = PerformanceCounterCategory.GetCategories()
            .FirstOrDefault(cat => cat.CategoryName == "Processor");
        var countersInCategory = processorCategory.GetCounters("_Total");

        DisplayCounter(countersInCategory.First(cnt => cnt.CounterName == "% Processor Time"));
    }

    private static void DisplayCounter(PerformanceCounter performanceCounter)
    {
        while (!Console.KeyAvailable)
        {
            Console.WriteLine("{0}\t{1} = {2}",
                performanceCounter.CategoryName, performanceCounter.CounterName, performanceCounter.NextValue());
            System.Threading.Thread.Sleep(1000);
        }
    }
}

Of course, the process will need appropiate permissions to access the performance counters you need.