PerformanceCounter Class

Updated: September 2010

Represents a Windows NT performance counter component.

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)

[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
	SharedState = true)]
public ref class PerformanceCounter sealed : public Component, 


The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The PerformanceCounter component can be used for both reading existing predefined or custom counters and publishing (writing) performance data to custom counters.

Important noteImportant Note:

In versions 1.0 and 1.1 of the .NET Framework, this class requires immediate callers to be fully trusted. In .NET Framework versions after version 1.1, this class requires PerformanceCounterPermission for specific actions. It is strongly recommended that PerformanceCounterPermission not be granted to semi-trusted code. The ability to read and write performance counters allows code to perform actions such as enumerating executing processes and obtaining information about them.

Caution noteCaution:

Passing a PerformanceCounter object to less-trusted code can create a security issue. Never pass performance counter objects, such as a PerformanceCounterCategory or PerformanceCounter, to less trusted code.

The predefined counters are too numerous to mention and are product-specific. For more information about .NET Framework performance counters, see Performance Counters in the .NET Framework.

To read from a performance counter, create an instance of the PerformanceCounter class, set the CategoryName, CounterName, and, optionally, the InstanceName or MachineName properties, and then call the NextValue method to take a performance counter reading.

To publish performance counter data, create one or more custom counters using the PerformanceCounterCategory::Create method, create an instance of the PerformanceCounter class, set the CategoryName, CounterName and, optionally, InstanceName or MachineName properties, and then call the IncrementBy, Increment, or Decrement methods, or set the RawValue property to change the value of your custom counter.


The Increment, IncrementBy, and Decrement methods use interlocks to update the counter value. This helps keep the counter value accurate in multithreaded or multiprocess scenarios, but also results in a performance penalty. If you do not need the accuracy that interlocked operations provide, you can update the RawValue property directly for up to a 5 times performance improvement. However, in multithreaded scenarios, some updates to the counter value might be ignored, resulting in inaccurate data.

The counter is the mechanism by which performance data is collected. The registry stores the names of all the counters, each of which is related to a specific area of system functionality. Examples include a processor's busy time, memory usage, or the number of bytes received over a network connection.

Each counter is uniquely identified through its name and its location. In the same way that a file path includes a drive, a directory, one or more subdirectories, and a file name, counter information consists of four elements: the computer, the category, the category instance, and the counter name.

The counter information must include the category, or performance object, that the counter measures data for. A computer's categories include physical components, such as processors, disks, and memory. There are also system categories, such as processes and threads. Each category is related to a functional element within the computer and has a set of standard counters assigned to it. These objects are listed in the Performance object drop-down list of the Add Counters dialog box within the Windows 2000 System Monitor, and you must include them in the counter path. Performance data is grouped by the category to which is it related.

In certain cases, several copies of the same category can exist. For example, several processes and threads run simultaneously, and some computers contain more than one processor. The category copies are called category instances, and each instance has a set of standard counters assigned to it. If a category can have more than one instance, an instance specification must be included in the counter information.

To obtain performance data for counters that required an initial or previous value for performing the necessary calculation, call the NextValue method twice and use the information returned as your application requires.


Performance counter categories installed with the .NET Framework 2.0 use separate shared memory, with each performance counter category having its own memory. You can specify the size of separate shared memory by creating a DWORD named FileMappingSize in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<category name>\Performance. The FileMappingSize value is set to the shared memory size of the category. The default size is 131072 decimal. If the FileMappingSize value is not present, the fileMappingSize attribute value for the performanceCounters element specified in the Machine.config file is used, causing additional overhead for configuration file processing. You can realize a performance improvement for application startup by setting the file mapping size in the registry. For more information about the file mapping size, see <performanceCounters> Element.

Windows 98, Windows Millennium Edition Platform Note: Performance counters are not supported on Windows 98 or Windows Millennium Edition (Me).

The following example shows the use of commonly referenced predefined counters to obtain performance data. The code example collects information about both the running application and the processor.

No code example is currently available or this language may not be supported.

The following code example demonstrates the use of the PerformanceCounter class to create and use an AverageCount64 counter type. The example creates categories, sets up counters, collects data from the counters, and calls the CounterSampleCalculator class to interpret the performance counter data. The intermediate and final results are displayed in the console window. For additional examples of other performance counter types, see the PerformanceCounterType enumeration.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;
using namespace System::Diagnostics;

// Output information about the counter sample. 
void OutputSample( CounterSample s )
   Console::WriteLine( "\r\n+++++++++++" );
   Console::WriteLine( "Sample values - \r\n" );
   Console::WriteLine( "   BaseValue        = {0}", s.BaseValue );
   Console::WriteLine( "   CounterFrequency = {0}", s.CounterFrequency );
   Console::WriteLine( "   CounterTimeStamp = {0}", s.CounterTimeStamp );
   Console::WriteLine( "   CounterType      = {0}", s.CounterType );
   Console::WriteLine( "   RawValue         = {0}", s.RawValue );
   Console::WriteLine( "   SystemFrequency  = {0}", s.SystemFrequency );
   Console::WriteLine( "   TimeStamp        = {0}", s.TimeStamp );
   Console::WriteLine( "   TimeStamp100nSec = {0}", s.TimeStamp100nSec );
   Console::WriteLine( "++++++++++++++++++++++" );

//    Description - This counter type shows how many items are processed, on average, 
//        during an operation. Counters of this type display a ratio of the items  
//        processed (such as bytes sent) to the number of operations completed. The   
//        ratio is calculated by comparing the number of items processed during the  
//        last interval to the number of operations completed during the last interval.  
// Generic type - Average 
//      Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number  
//        of items processed during the last sample interval and the denominator (D)  
//        represents the number of operations completed during the last two sample  
//        intervals.  
//    Average (Nx - N0) / (Dx - D0)   
//    Example PhysicalDisk\ Avg. Disk Bytes/Transfer  
float MyComputeCounterValue( CounterSample s0, CounterSample s1 )
   float numerator = (float)s1.RawValue - (float)s0.RawValue;
   float denomenator = (float)s1.BaseValue - (float)s0.BaseValue;
   float counterValue = numerator / denomenator;
   return counterValue;

bool SetupCategory()
   if (  !PerformanceCounterCategory::Exists( "AverageCounter64SampleCategory" ) )
      CounterCreationDataCollection^ CCDC = gcnew CounterCreationDataCollection;

      // Add the counter.
      CounterCreationData^ averageCount64 = gcnew CounterCreationData;
      averageCount64->CounterType = PerformanceCounterType::AverageCount64;
      averageCount64->CounterName = "AverageCounter64Sample";
      CCDC->Add( averageCount64 );

      // Add the base counter.
      CounterCreationData^ averageCount64Base = gcnew CounterCreationData;
      averageCount64Base->CounterType = PerformanceCounterType::AverageBase;
      averageCount64Base->CounterName = "AverageCounter64SampleBase";
      CCDC->Add( averageCount64Base );

      // Create the category.
      PerformanceCounterCategory::Create( "AverageCounter64SampleCategory", "Demonstrates usage of the AverageCounter64 performance counter type.", CCDC );
      return (true);
      Console::WriteLine( "Category exists - AverageCounter64SampleCategory" );
      return (false);

void CreateCounters( PerformanceCounter^% PC, PerformanceCounter^% BPC )

   // Create the counters.
   PC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64Sample",false );

   BPC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64SampleBase",false );
   PC->RawValue = 0;
   BPC->RawValue = 0;
void CollectSamples( ArrayList^ samplesList, PerformanceCounter^ PC, PerformanceCounter^ BPC )
   Random^ r = gcnew Random( DateTime::Now.Millisecond );

   // Loop for the samples. 
   for ( int j = 0; j < 100; j++ )
      int value = r->Next( 1, 10 );
      Console::Write( "{0} = {1}", j, value );
      PC->IncrementBy( value );
      if ( (j % 10) == 9 )
         OutputSample( PC->NextSample() );
         samplesList->Add( PC->NextSample() );
      System::Threading::Thread::Sleep( 50 );

void CalculateResults( ArrayList^ samplesList )
   for ( int i = 0; i < (samplesList->Count - 1); i++ )
      // Output the sample.
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );

      // Use .NET to calculate the counter value.
      Console::WriteLine( ".NET computed counter value = {0}", CounterSampleCalculator::ComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );

      // Calculate the counter value manually.
      Console::WriteLine( "My computed counter value = {0}", MyComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );

int main()
   ArrayList^ samplesList = gcnew ArrayList;
   PerformanceCounter^ PC;
   PerformanceCounter^ BPC;
   CreateCounters( PC, BPC );
   CollectSamples( samplesList, PC, BPC );
   CalculateResults( samplesList );


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0




September 2010

Corrected thread safety information; type is not thread safe.

Content bug fix.

October 2009

Added a basic example.

Customer feedback.

July 2009

Added a link to the .NET Framework performance counters

Customer feedback.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2015 Microsoft