Visual C# Developer Center > Visual C# Forums > Visual C# General > System.Diagnostics.PerformanceCounter NextValue(): why so slow?
Ask a questionAsk a question
 

QuestionSystem.Diagnostics.PerformanceCounter NextValue(): why so slow?

  • Tuesday, November 03, 2009 3:59 PMRobert Varga Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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?

    Thanks,
    Rob

All Replies

  • Wednesday, November 04, 2009 1:32 PMRobert Varga Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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?

    Thanks,
    Rob
  • Friday, November 06, 2009 8:47 AMChao KuoMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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.
    Thanks
    Chao
  • Sunday, November 08, 2009 5:49 PMRobert Varga Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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.

    Cheers,
    Rob