4

I have kind of library which uses a bunch of its own perf counters. But I want my library works fine even if that perf counters weren't installed.

So I've created wrappers aroung PerformanceCounter and on the first use check if PerfCounter exists or not. If they exists then I'm using native PerformanceCounter instead I'm using a wrapper which do nothing.

So to check perf counter existence I use PerformanceCounterCategory.Exists

The problem is that if there isn't such category then PerformanceCounterCategory.Exists call takes (on my machine) about 10 seconds! Needless to say it's too slow.

What can I do?

Code to try it by youself: using System; using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var ts = Stopwatch.StartNew();
        var res = PerformanceCounterCategory.Exists("XYZ");
        Console.WriteLine(ts.ElapsedMilliseconds);
        Console.WriteLine("result:" + res);
}
}
Shrike
  • 9,218
  • 7
  • 68
  • 105

2 Answers2

6

This is something that it seems cannot be avoided. From MSDN:

Use of the Exists method can result in a noticeable performance penalty while all performance counters on the machine are checked for availability. If you are only writing to a performance counter, you can avoid the global search for performance counters by creating the performance counter when the application is installed and assuming the category exists when accessing the counter. There is no way to avoid the performance counter search when reading from performance counters.

Emphasis is mine.

João Angelo
  • 56,552
  • 12
  • 145
  • 147
0

This is a 8 years old question, but just sharing what fixed for me:

The performance counters setup time in my application dropped from 2:30 minutes to around 20 seconds by ensuring it was being executed as a 64bit process. The interesting is that I had the performance issue only in a Windows 2012 VM. No problems in Windows 10.

eduardobr
  • 146
  • 15