System.Diagnostics.PerformanceCounter NextValue(): why so slow? RRS feed

  • Question

  • Hi All,

    I'm finding that calling NextValue() on a PerformanceCounter is extremely slow.  I say slow, because when I add the exact same counters (as my code uses) to perfmon, the sampling takes place every second without issue.  To sample the same set of counters (instances of the Thread/Processor Time counter), my code takes 40 seconds+.

    My code, in its simplest form, is doing this:

            private void Foo()
                PerformanceCounter c = new PerformanceCounter();
                c.MachineName = "AServer";
                c.CategoryName = "Thread";
                c.CounterName = "% Processor Time";
                foreach (instance k in col) //about 60ish...
                    c.InstanceName = k.InstanceName;
                    c.NextValue(); //is assigned to simple var

    (And yes, I realise I should be calling NextValue twice initially).

    As I mentioned, the same set of 60ish counters in perfmon sample quite happily.  Am I doing something stupid, or is there a quicker way to "batch" sample instances?

    Tuesday, November 3, 2009 3:59 PM

All replies

  • Really, no one has run into the same issue?

    Does anyone know how to efficiently sample multiple instances - is there a way to "batch sample" several instances in the way that perfmon does?

    Wednesday, November 4, 2009 1:32 PM
  • Hello, Robert
    What's your version of your .net framework? .Net Framework 1.1 has a performance issue when your run multi-thread instance. For 2.0 upper, Could you elaborate more about your code? I did not face this issue on my PC.
    Friday, November 6, 2009 8:47 AM
  • Hi Chao,

    I'm running it on vista on .net 3.5.

    When I add the instances in perfrmon, they update quite happily every second (all 60).  Whereas in my code (as per above) as I need to call .NextValue() for each of the 60 instances, it crawls - the completion of the foreach loop takes 30- 40 seconds.

    I really only notice this if I'm trying to connect/run the code on remote servers with high latency.

    Sunday, November 8, 2009 5:49 PM
  • I am using .net 4.0. I am facing similar problem. I am trying to read exchange server and AD performance counters,both as localhost and remotehost. I don't see any significant difference between local and remote deployment.

    Is there any appraoch that can make things faster.




    Monday, June 28, 2010 9:32 AM
  • I am having the same issue with .net 2.0 and about 45 counters. Found this link that purports to solve the problem... http://support.microsoft.com/kb/834672

    Haven't tried it though.

    Thursday, September 1, 2011 7:39 AM
  • Many thanks for the update Laurence.
    Friday, August 24, 2012 3:40 PM