SJ.
SJ.

Reputation: 123

Custom Performance Counter / Minute in .NET

I'm trying to create a custom performance counter in C# based on per minute.

So far, I've seen only RateOfCountsPerSecond32 or RateOfCountsPerSecond64 available.

Does anybody know what are options for creating a custom counter based on per minute?

Upvotes: 3

Views: 2870

Answers (2)

Evgeniy Senetskiy
Evgeniy Senetskiy

Reputation: 166

By default PerfMon pulls data every second. In order to get permanent image in Windows performance monitor chart, I've wrote custom counter for measure rate of count per minute. After working for one minute I become receive data from my counter. Note that accuracy doesn't important for me.

Code snippet look like this:

class PerMinExample
{
    private static PerformanceCounter _pcPerSec;
    private static PerformanceCounter _pcPerMin;
    private static Timer _timer = new Timer(CallBack, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    private static Queue<CounterSample> _queue = new Queue<CounterSample>();

    static PerMinExample()
    {
        // RateOfCountsPerSecond32
        _pcPerSec = new PerformanceCounter("Category", "ORDERS PER SECOND", false);

        // NumberOfItems32
        _pcPerMin = new PerformanceCounter("Category", "ORDERS PER MINUTE", false);
        _pcPerSec.RawValue = 0;
        _pcPerMin.RawValue = 0;
    }

    public void CountSomething()
    {
        _pcPerSec.Increment();
    }

    private static void CallBack(Object o)
    {
        CounterSample sample = _pcPerSec.NextSample();

        _queue.Enqueue(sample);
        if (_queue.Count <= 60)
            return;

        CounterSample prev = _queue.Dequeue();

        Single numerator = (Single)sample.RawValue - (Single)prev.RawValue;
        Single denomenator = 
            (Single)(sample.TimeStamp - prev.TimeStamp) 
            / (Single)(sample.SystemFrequency) / 60;
        Single counterValue = numerator / denomenator;

        _pcPerMin.RawValue = (Int32)Math.Ceiling(counterValue);

        Console.WriteLine("ORDERS PER SEC: {0}", _pcPerSec.NextValue());
        Console.WriteLine("ORDERS PER MINUTE: {0}", _pcPerMin.NextValue());
    }
}

Upvotes: 3

Alan McBee
Alan McBee

Reputation: 4320

This won't be directly supported. You'll have to computer the rate per minute yourself, and then use a NumberOfItems32 or NumberOfItems64 counter to display the rate. Using a helpful name like "Count / minute" will make it clear what the value is. You'll just update the counter every minute. A background (worker) thread would be a good place to do that.

Alternately, you can just depend upon the monitoring software. Use a NumberOfItems32/64 counter, but have the monitoring software do the per-minute computation. The PerfMon tool built into Windows doesn't do this, but there's no reason it couldn't.

Upvotes: 3

Related Questions