Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

PerformanceCounter Class

Represents a Windows NT performance counter component.

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

public sealed class PerformanceCounter : Component, ISupportInitialize
public final class PerformanceCounter extends Component implements ISupportInitialize
public final class PerformanceCounter extends Component implements ISupportInitialize

NoteNote

The HostProtectionAttribute attribute applied to this class 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.

NoteImportant:

In versions 1.0 and 1.1 of the .NET Framework, this class requires immediate callers to be fully trusted. In version 2.0 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.

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.

NoteNote

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.

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


using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class App {

	private static PerformanceCounter PC;
	private static PerformanceCounter BPC;

	public static void Main()
	{	
	
		ArrayList samplesList = new ArrayList();

		SetupCategory();
		CreateCounters();
		CollectSamples(samplesList);
		CalculateResults(samplesList);

	}
	

	private static bool SetupCategory()
	{		
		if ( !PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") ) 
		{

			CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
			
			// Add the counter.
			CounterCreationData averageCount64 = new CounterCreationData();
			averageCount64.CounterType = PerformanceCounterType.AverageCount64;
			averageCount64.CounterName = "AverageCounter64Sample";
			CCDC.Add(averageCount64);
	        
	        // Add the base counter.
			CounterCreationData averageCount64Base = new 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);
		}
		else
		{
			Console.WriteLine("Category exists - AverageCounter64SampleCategory");
			return(false);
		}
	}
	
	private static void CreateCounters()
	{
		// Create the counters.

		PC = new PerformanceCounter("AverageCounter64SampleCategory", 
			"AverageCounter64Sample", 
			false);
		

		BPC = new PerformanceCounter("AverageCounter64SampleCategory", 
			"AverageCounter64SampleBase", 
			false);
		
		
		PC.RawValue=0;
		BPC.RawValue=0;
	}
	
	private static void CollectSamples(ArrayList samplesList)
	{
		
		Random r = new Random( DateTime.Now.Millisecond );

		// Loop for the samples.
		for (int j = 0; j < 100; j++) 
		{
	        
			int value = r.Next(1, 10);
			Console.Write(j + " = " + value);

			PC.IncrementBy(value);

			BPC.Increment();

			if ((j % 10) == 9) 
			{
				OutputSample(PC.NextSample());
				samplesList.Add( PC.NextSample() );
			}
			else
				Console.WriteLine();
	        
			System.Threading.Thread.Sleep(50);
		}

	}
	
	private static void CalculateResults(ArrayList samplesList)
	{
		for(int i = 0; i < (samplesList.Count - 1); i++)
		{
			// Output the sample.
			OutputSample( (CounterSample)samplesList[i] );
			OutputSample( (CounterSample)samplesList[i+1] );

			// Use .NET to calculate the counter value.
			Console.WriteLine(".NET computed counter value = " +
				CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
				(CounterSample)samplesList[i+1]) );

			// Calculate the counter value manually.
			Console.WriteLine("My computed counter value = " + 
				MyComputeCounterValue((CounterSample)samplesList[i],
				(CounterSample)samplesList[i+1]) );

		}
	}
	
	
	//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
	//	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 
	//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
	private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
	{
		Single numerator = (Single)s1.RawValue - (Single)s0.RawValue;
		Single denomenator = (Single)s1.BaseValue - (Single)s0.BaseValue;
		Single counterValue = numerator / denomenator;
		return(counterValue);
	}
		
	// Output information about the counter sample.
	private static void OutputSample(CounterSample s)
	{
		Console.WriteLine("\r\n+++++++++++");
		Console.WriteLine("Sample values - \r\n");
		Console.WriteLine("   BaseValue        = " + s.BaseValue);
		Console.WriteLine("   CounterFrequency = " + s.CounterFrequency);
		Console.WriteLine("   CounterTimeStamp = " + s.CounterTimeStamp);
		Console.WriteLine("   CounterType      = " + s.CounterType);
		Console.WriteLine("   RawValue         = " + s.RawValue);
		Console.WriteLine("   SystemFrequency  = " + s.SystemFrequency);
		Console.WriteLine("   TimeStamp        = " + s.TimeStamp);
		Console.WriteLine("   TimeStamp100nSec = " + s.TimeStamp100nSec);
		Console.WriteLine("++++++++++++++++++++++");
	}
}

import System.*;  
import System.Collections.*;  
import System.Collections.Specialized.*;  
import System.Diagnostics.*;  

public class App
{
    private static PerformanceCounter pc;
    private static PerformanceCounter bpc;

    public static void main(String[] args)
    {
        ArrayList samplesList = new ArrayList();
        SetupCategory();
        CreateCounters();
        CollectSamples(samplesList);
        CalculateResults(samplesList);
    } //main

    private static boolean SetupCategory()
    {
        if (!(PerformanceCounterCategory.Exists(
            "AverageCounter64SampleCategory"))) {
            CounterCreationDataCollection ccdc = 
                new CounterCreationDataCollection();
            // Add the counter.
            CounterCreationData averageCount64 = new CounterCreationData();
            averageCount64.
                set_CounterType(PerformanceCounterType.AverageCount64);
            averageCount64.set_CounterName("AverageCounter64Sample");
            ccdc.Add(averageCount64);
            // Add the base counter.
            CounterCreationData averageCount64Base = new CounterCreationData();
            averageCount64Base.set_CounterType(PerformanceCounterType.
                AverageBase);
            averageCount64Base.set_CounterName("AverageCounter64SampleBase");
            ccdc.Add(averageCount64Base);
            // Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance "
                + "counter type.", ccdc);
            return true;
        }
        else {
            Console.WriteLine("Category exists - AverageCounter64SampleCategory");
            return false;
        }
    } //SetupCategory

    private static void CreateCounters()
    {
        // Create the counters.
        pc = new PerformanceCounter("AverageCounter64SampleCategory",
            "AverageCounter64Sample", false);
        bpc = new PerformanceCounter("AverageCounter64SampleCategory",
            "AverageCounter64SampleBase", false);
        pc.set_RawValue(0);
        bpc.set_RawValue(0);
    } //CreateCounters

    private static void CollectSamples(ArrayList samplesList)
    {
        Random r = new Random(DateTime.get_Now().get_Millisecond());
        // Loop for the samples.
        for (int j = 0; j < 100; j++) {
            int value = r.Next(1, 10);
            Console.Write(j + " = " + value);
            pc.IncrementBy(value);
            bpc.Increment();

            if (j % 10 == 9) {
                OutputSample(pc.NextSample());
                samplesList.Add(pc.NextSample());
            }
            else {
                Console.WriteLine();
            }
            System.Threading.Thread.Sleep(50);
        }
    } //CollectSamples

    private static void CalculateResults(ArrayList samplesList)
    {
        for (int i = 0; i < samplesList.get_Count() - 1; i++) {
            // Output the sample.
            OutputSample((CounterSample)samplesList.get_Item(i));
            OutputSample((CounterSample)samplesList.get_Item(i + 1));
            // Use.NET to calculate the counter value.
            Console.WriteLine(".NET computed counter value = " 
                + CounterSampleCalculator.ComputeCounterValue((CounterSample)
                samplesList.get_Item(i), 
                (CounterSample)samplesList.get_Item(i + 1)));
            // Calculate the counter value manually.
            Console.WriteLine("My computed counter value = "
                + MyComputeCounterValue((CounterSample)samplesList.get_Item(i),
                (CounterSample)samplesList.get_Item(i + 1)));
        }
    } //CalculateResults

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //++++++++
    //    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 
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //++++++++
    private static float MyComputeCounterValue(CounterSample s0,
        CounterSample s1)
    {
        float numerator = (float)s1.get_RawValue() - (float)s0.get_RawValue();
        float denomenator = (float)s1.get_BaseValue() - (float)s0.
            get_BaseValue();
        float counterValue = numerator / denomenator;
        return counterValue;
    } //MyComputeCounterValue

    // Output information about the counter sample.
    private static void OutputSample(CounterSample s)
    {
        Console.WriteLine("\r\n+++++++++++");
        Console.WriteLine("Sample values - \r\n");
        Console.WriteLine("   BaseValue        = " + s.get_BaseValue());
        Console.WriteLine("   CounterFrequency = " + s.get_CounterFrequency());
        Console.WriteLine("   CounterTimeStamp = " + s.get_CounterTimeStamp());
        Console.WriteLine("   CounterType      = " + s.get_CounterType());
        Console.WriteLine("   RawValue         = " + s.get_RawValue());
        Console.WriteLine("   SystemFrequency  = " + s.get_SystemFrequency());
        Console.WriteLine("   TimeStamp        = " + s.get_TimeStamp());
        Console.WriteLine("   TimeStamp100nSec = " + s.get_TimeStamp100nSec());
        Console.WriteLine("++++++++++++++++++++++");
    } //OutputSample
} //App

System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
      System.Diagnostics.PerformanceCounter

This type is safe for multithreaded operations.

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0, 1.1, 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft