Export (0) Print
Expand All
Expand Minimize

PerformanceCounterType Enumeration

Specifies the formula used to calculate the NextValue method for a PerformanceCounter instance.

[Visual Basic]
<Serializable>
Public Enum PerformanceCounterType
[C#]
[Serializable]
public enum PerformanceCounterType
[C++]
[Serializable]
__value public enum PerformanceCounterType
[JScript]
public
   Serializable
enum PerformanceCounterType

Remarks

Some counter types represent raw data, while others represent calculated values that are based on one or more counter samples. The following categories classify the types of counters available.

  • Average: measure a value over time and display the average of the last two measurements. Associated with each average counter is a base counter that tracks the number of samples involved.
  • Difference: subtract the last measurement from the previous one and display the difference, if it is positive; if negative, they display a zero.
  • Instantaneous: display the most recent measurement.
  • Percentage: display calculated values as a percentage.
  • Rate: sample an increasing count of events over time and divide the cache in count values by the change in time to display a rate of activity.

When sampling performance counter data, using a counter type that represents an average can make raw data values meaningful for your use. For example, the raw data counter NumberOfItems64 can expose data that is fairly random from sample to sample. The formula for an average calculation of the values that the counter returns would be (X0 +X 1 ++X n)/n, where each X i is a raw counter sample.

Rate counters are similar to average counters, but more useful for situations in which the rate increases as a resource is used. A formula that quickly calculates the average is ((Xn -X 0)/(T n -T 0))/ frequency, where each X i is a counter sample and each T i is the time that the corresponding sample was taken. The result is the average usage per second.

Note   Unless otherwise indicated, the time base is seconds.

When instrumenting applications (creating and writing custom performance counters), you might be working with performance counter types that rely on an accompanying base counter that is used in the calculations. The base counter must be immediately after its associated counter in the CounterCreationDataCollection collection your application uses. The following table lists the base counter types with their corresponding performance counter types.

Base counter type Performance counter types
AverageBase AverageTimer32

AverageCount64

CounterMultiBase CounterMultiTimer

CounterMultiTimerInverse

CounterMultiTimer100Ns

CounterMultiTimer100NsInverse

RawBase RawFraction
SampleBase SampleCounter

SampleFraction

Members

Member name Description
AverageBase A base counter that is used in the calculation of time or count averages, such as AverageTimer32 and AverageCount64. Stores the denominator for calculating a counter to present "time per operation" or "count per operation".
AverageCount64 An average counter that shows how many items are processed, on average, during an operation. Counters of this type display a ratio of the items processed 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.

Formula: (N1 -N 0)/(B 1 -B 0), where N 1 and N 0 are performance counter readings, and the B 1 and B 0 are their corresponding AverageBase values. Thus, the numerator represents the numbers of items processed during the sample interval, and the denominator represents the number of operations completed during the sample interval.

Counters of this type include PhysicalDisk\ Avg. Disk Bytes/Transfer.

AverageTimer32 An average counter that measures the time it takes, on average, to complete a process or operation. Counters of this type display a ratio of the total elapsed time of the sample interval to the number of processes or operations completed during that time. This counter type measures time in ticks of the system clock.

Formula: ((N1 -N 0)/F)/(B 1 -B 0), where N 1 and N 0 are performance counter readings, B 1 and B 0 are their corresponding AverageBase values, and F is the number of ticks per second. The value of F is factored into the equation so that the result can be displayed in seconds. Thus, the numerator represents the numbers of ticks counted during the last sample interval, F represents the frequency of the ticks, and the denominator represents the number of operations completed during the last sample interval.

Counters of this type include PhysicalDisk\ Avg. Disk sec/Transfer.

CounterDelta32 A difference counter that shows the change in the measured attribute between the two most recent sample intervals.

Formula: N1 -N 0, where N 1 and N 0 are performance counter readings.

CounterDelta64 A difference counter that shows the change in the measured attribute between the two most recent sample intervals. It is the same as the CounterDelta32 counter type except that is uses larger fields to accomodate larger values.

Formula: N1 -N 0, where N 1 and N 0 are performance counter readings.

CounterMultiBase A base counter that indicates the number of items sampled. It is used as the denominator in the calculations to get an average among the items sampled when taking timings of multiple, but similar items. Used with CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, and CounterMultiTimer100NsInverse.
CounterMultiTimer A percentage counter that displays the active time of one or more components as a percentage of the total time of the sample interval. Because the numerator records the active time of components operating simultaneously, the resulting percentage can exceed 100 percent.

This counter is a multitimer. Multitimers collect data from more than one instance of a component, such as a processor or disk. This counter type differs from CounterMultiTimer100Ns in that it measures time in units of ticks of the system performance timer, rather than in 100 nanosecond units.

Formula: ((N1 - N 0)/ (D 1 - D 0)) x 100/ B, where N 1 and N 0 are performance counter readings, D 1 and D 0 are their corresponding time readings in 100-nanosecond units, and the variable B denotes the base count for the monitored components (using a base counter of type CounterMultiBase). Thus, the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval.

CounterMultiTimer100Ns A percentage counter that shows the active time of one or more components as a percentage of the total time of the sample interval. It measures time in 100 nanosecond (ns) units.

This counter type is a multitimer. Multitimers are designed to monitor more than one instance of a component, such as a processor or disk.

Formula: ((N1 - N 0)/ (D 1 - D 0)) x 100/ B, where N 1 and N 0 are performance counter readings, D 1 and D 0 are their corresponding time readings in 100-nanosecond units, and the variable B denotes the base count for the monitored components (using a base counter of type CounterMultiBase). Thus, the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval.

CounterMultiTimer100NsInverse A percentage counter that shows the active time of one or more components as a percentage of the total time of the sample interval. Counters of this type measure time in 100 nanosecond (ns) units. They derive the active time by measuring the time that the components were not active and subtracting the result from multiplying 100 percent by the number of objects monitored.

This counter type is an inverse multitimer. Multitimers are designed to monitor more than one instance of a component, such as a processor or disk. Inverse counters measure the time that a component is not active and derive its active time from the measurement of inactive time

Formula: (B - ((N1 - N 0)/ (D 1 - D 0))) x 100, where the denominator represents the total elapsed time of the sample interval, the numerator represents the time during the interval when monitored components were inactive, and B represents the number of components being monitored, using a base counter of type CounterMultiBase.

CounterMultiTimerInverse A percentage counter that shows the active time of one or more components as a percentage of the total time of the sample interval. It derives the active time by measuring the time that the components were not active and subtracting the result from 100 percent by the number of objects monitored.

This counter type is an inverse multitimer. Multitimers monitor more than one instance of a component, such as a processor or disk. Inverse counters measure the time that a component is not active and derive its active time from that measurement.

This counter differs from CounterMultiTimer100NsInverse in that it measures time in units of ticks of the system performance timer, rather than in 100 nanosecond units.

Formula: (B- ((N1 - N 0)/ (D 1 - D 0))) x 100, where the denominator represents the total elapsed time of the sample interval, the numerator represents the time during the interval when monitored components were inactive, and B represents the number of components being monitored, using a base counter of type CounterMultiBase.

CounterTimer A percentage counter that shows the average time that a component is active as a percentage of the total sample time.

Formula: (N1 - N 0)/ (D 1 - D 0), where N 1 and N 0 are performance counter readings, and D 1 and D 0 are their corresponding time readings. Thus, the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval.

CounterTimerInverse A percentage counter that displays the average percentage of active time observed during sample interval. The value of these counters is calculated by monitoring the percentage of time that the service was inactive and then subtracting that value from 100 percent.

This is an inverse counter type. Inverse counters measure the time that a component is note active and derive the active time from that measurement. This counter type is the same as CounterTimer100NsInv except that it measures time in units of ticks of the system performance timer rather than in 100 nanosecond units.

Formula: (1- ((N1 - N 0)/ (D 1 - D 0))) x 100, where the numerator represents the time during the interval when the monitored components were inactive, and the denominator represents the total elapsed time of the sample interval.

CountPerTimeInterval32 An average counter designed to monitor the average length of a queue to a resource over time. It shows the difference between the queue lengths observed during the last two sample intervals divided by the duration of the interval. This type of counter is typically used to track the number of items that are queued or waiting.

Formula: (N1 - N 0)/ (D 1 - D 0), where the numerator represents the number of items in the queue and the denominator represents the time elapsed during the last sample interval.

CountPerTimeInterval64 An average counter that monitors the average length of a queue to a resource over time. Counters of this type display the difference between the queue lengths observed during the last two sample intervals, divided by the duration of the interval. This counter type is the same as CountPerTimeInterval32 except that it uses larger fields to accommodate larger values. This type of counter is typically used to track a high-volume or very large number of items that are queued or waiting.

Formula: (N1 - N 0)/ (D 1 - D 0), where the numerator represents the number of items in a queue and the denominator represents the time elapsed during the sample interval.

ElapsedTime A difference timer that shows the total time between when the component or process started and the time when this value is calculated.

Formula: (D0 - N 0)/ F, where D 0 represents the current time, N 0 represents the time the object was started, and F represents the number of time units that elapse in one second. The value of F is factored into the equation so that the result can be displayed in seconds.

Counters of this type include System\ System Up Time.

NumberOfItems32 An instantaneous counter that shows the most recently observed value. Used, for example, to maintain a simple count of items or operations.

Formula: None. Does not display an average, but shows the raw data as it is collected.

Counters of this type include Memory\Available Bytes.

NumberOfItems64 An instantaneous counter that shows the most recently observed value. Used, for example, to maintain a simple count of a very large number of items or operations. It is the same as NumberOfItems32 except that it uses larger fields to accommodate larger values.

Formula: None. Does not display an average, but shows the raw data as it is collected.

NumberOfItemsHEX32 An instantaneous counter that shows the most recently observed value in hexadecimal format. Used, for example, to maintain a simple count of items or operations.

Formula: None. Does not display an average, but shows the raw data as it is collected.

NumberOfItemsHEX64 An instantaneous counter that shows the most recently observed value. Used, for example, to maintain a simple count of a very large number of items or operations. It is the same as NumberOfItemsHEX32 except that it uses larger fields to accommodate larger values.

Formula: None. Does not display an average, but shows the raw data as it is collected

RateOfCountsPerSecond32 A difference counter that shows the average number of operations completed during each second of the sample interval. Counters of this type measure time in ticks of the system clock.

Formula: (N1 - N 0)/ ( (D 1 -D 0)/ F), where N 1 and N 0 are performance counter readings, D 1 and D 0 are their corresponding time readings, and F represents the number of ticks per second. Thus, the numerator represents the number of operations performed during the last sample interval, the denominator represents the number of ticks elapsed during the last sample interval, and F is the frequency of the ticks. The value of F is factored into the equation so that the result can be displayed in seconds.

Counters of this type include System\ File Read Operations/sec.

RateOfCountsPerSecond64 A difference counter that shows the average number of operations completed during each second of the sample interval. Counters of this type measure time in ticks of the system clock. This counter type is the same as the RateOfCountsPerSecond32 type, but it uses larger fields to accommodate larger values to track a high-volume number of items or operations per second, such as a byte-transmission rate.

Formula: (N1 - N 0)/ ( (D 1 -D 0)/ F), where N 1 and N 0 are performance counter readings, D 1 and D 0 are their corresponding time readings, and F represents the number of ticks per second. Thus, the numerator represents the number of operations performed during the last sample interval, the denominator represents the number of ticks elapsed during the last sample interval, and F is the frequency of the ticks. The value of F is factored into the equation so that the result can be displayed in seconds.

Counters of this type include System\ File Read Bytes/sec.

RawBase A base counter that stores the denominator of a counter that presents a general arithmetic fraction. Check that this value is greater than zero before using it as the denominator in a RawFraction value calculation.
RawFraction An instantaneous percentage counter that shows the ratio of a subset to its set as a percentage. For example, it compares the number of bytes in use on a disk to the total number of bytes on the disk. Counters of this type display the current percentage only, not an average over time.

Formula: (N0/ D 0) x 100, where D 0 represents a measured attribute (using a base counter of type RawBase) and N0 represents one component of that attribute.

Counters of this type include Paging File\% Usage Peak.

SampleBase A base counter that stores the number of sampling interrupts taken and is used as a denominator in the sampling fraction. The sampling fraction is the number of samples that were 1 (or true) for a sample interrupt. Check that this value is greater than zero before using it as the denominator in a calculation of SampleCounter or SampleFraction.
SampleCounter An average counter that shows the average number of operations completed in one second. When a counter of this type samples the data, each sampling interrupt returns one or zero. The counter data is the number of ones that were sampled. It measures time in units of ticks of the system performance timer.

Formula: (N1 - N 0)/ ((D 1 - D 0)/ F), where N 1 and N 0 are performance counter readings, D 1 and D 0 are their corresponding SampleBase values, and F is the number of ticks that elapse in one second. Thus, the numerator represents the number of operations completed and the denominator represents elapsed time in units of ticks of the system performance timer. F is factored into the equation so that the result can be displayed in seconds.

SampleFraction A percentage counter that shows the average ratio of hits to all operations during the last two sample intervals.

Formula: ((N1 - N 0)/ (D 1 - D 0)) x 100, where the numerator represents the number of successful operations during the last sample interval, and the denominator represents the change in the number of all operations (of the type measured) completed during the sample interval, using counters of type SampleBase.

Counters of this type include Cache\Pin Read Hits %.

Timer100Ns A percentage counter that shows the active time of a component as a percentage of the total elapsed time of the sample interval. It measures time in units of 100 nanoseconds (ns). Counters of this type are designed to measure the activity of one component at a time.

Formula: (N1 - N 0)/ (D 1 - D 0) x 100, where the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval.

Counters of this type include Processor\ % User Time.

Timer100NsInverse A percentage counter that shows the average percentage of active time observed during the sample interval.

This is an inverse counter. Counters of this type calculate active time by measuring the time that the service was inactive and then subtracting the percentage of active time from 100 percent.

Formula: (1- ((N1 - N 0)/ (D 1 - D 0))) x 100, where the numerator represents the time during the interval when the monitored components were inactive, and the denominator represents the total elapsed time of the sample interval.

Counters of this type include Processor\ % Processor Time.

Example

[Visual Basic, C#, C++] The following examples demonstrate several of the counter types in the PerformanceCounterType enumeration.

[Visual Basic, C#, C++] AverageCount64

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class App
   
   Private Shared PC As PerformanceCounter
   Private Shared BPC As PerformanceCounter
   
   
   Public Shared Sub Main()
      
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 'Main
    
   
   
   Private Shared Function SetupCategory() As Boolean
      If Not PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") Then
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim averageCount64 As New CounterCreationData()
         averageCount64.CounterType = PerformanceCounterType.AverageCount64
         averageCount64.CounterName = "AverageCounter64Sample"
         CCDC.Add(averageCount64)
         
         ' Add the base counter.
         Dim averageCount64Base As 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
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counters.

      PC = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64Sample", False)
      
      BPC = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64SampleBase", False)
      
      
      PC.RawValue = 0
      BPC.RawValue = 0
   End Sub 'CreateCounters
   
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         
         Dim value As Integer = r.Next(1, 10)
         Console.Write((j + " = " + value))
         
         PC.IncrementBy(value)
         
         BPC.Increment()
         
         If j Mod 10 = 9 Then
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         Else
            Console.WriteLine()
         End If 
         System.Threading.Thread.Sleep(50)
      Next j
   End Sub 'CollectSamples
    
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      For i = 0 To (samplesList.Count - 1) - 1
         ' Output the sample.
         OutputSample(CType(samplesList(i), CounterSample))
         OutputSample(CType(samplesList((i + 1)), CounterSample))
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
      Next i
   End Sub '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 Shared Function MyComputeCounterValue(s0 As CounterSample, s1 As CounterSample) As [Single]
      Dim numerator As [Single] = CType(s1.RawValue, [Single]) - CType(s0.RawValue, [Single])
      Dim denomenator As [Single] = CType(s1.BaseValue, [Single]) - CType(s0.BaseValue, [Single])
      Dim counterValue As [Single] = numerator / denomenator
      Return counterValue
   End Function 'MyComputeCounterValue
   
   
   ' Output information about the counter sample.
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
      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("++++++++++++++++++++++")
   End Sub 'OutputSample
End Class 'App

[C#] 

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("++++++++++++++++++++++");
    }
}

[C++] 
#using <mscorlib.dll>
#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(S"\r\n+++++++++++");
    Console::WriteLine(S"Sample values - \r\n");
    Console::WriteLine(S"   BaseValue        = {0}", __box(s.BaseValue));
    Console::WriteLine(S"   CounterFrequency = {0}", __box(s.CounterFrequency));
    Console::WriteLine(S"   CounterTimeStamp = {0}", __box(s.CounterTimeStamp));
    Console::WriteLine(S"   CounterType      = {0}", __box(s.CounterType));
    Console::WriteLine(S"   RawValue         = {0}", __box(s.RawValue));
    Console::WriteLine(S"   SystemFrequency  = {0}", __box(s.SystemFrequency));
    Console::WriteLine(S"   TimeStamp        = {0}", __box(s.TimeStamp));
    Console::WriteLine(S"   TimeStamp100nSec = {0}", __box(s.TimeStamp100nSec));
    Console::WriteLine(S"++++++++++++++++++++++");
}

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//    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(S"AverageCounter64SampleCategory")) {

        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

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

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

        // Create the category.
        PerformanceCounterCategory::Create(S"AverageCounter64SampleCategory", 
            S"Demonstrates usage of the AverageCounter64 performance counter type.", 
            CCDC);

        return(true);
    } else {
        Console::WriteLine(S"Category exists - AverageCounter64SampleCategory");
        return(false);
    }
}

void CreateCounters(PerformanceCounter*& PC, PerformanceCounter*& BPC) {
    // Create the counters.

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

    PC->RawValue=0;
    BPC->RawValue=0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC, PerformanceCounter* BPC) {

    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(S"{0} = {1}", __box(j), __box(value));

        PC->IncrementBy(value);

        BPC->Increment();

        if ((j % 10) == 9) {
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        } else
            Console::WriteLine();

        System::Threading::Thread::Sleep(50);
    }
}

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

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

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

int main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;
    PerformanceCounter* BPC;

    SetupCategory();
    CreateCounters(PC, BPC);
    CollectSamples(samplesList, PC, BPC);
    CalculateResults(samplesList);
}

[Visual Basic, C#, C++] AverageTimer32

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic

Public Class App

   Private Shared PC As PerformanceCounter
   Private Shared BPC As PerformanceCounter
   
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 
     
   
   Private Shared Function SetupCategory() As Boolean
      
      If Not PerformanceCounterCategory.Exists("AverageTimer32SampleCategory") Then
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim averageTimer32 As New CounterCreationData()
         averageTimer32.CounterType = PerformanceCounterType.AverageTimer32
         averageTimer32.CounterName = "AverageTimer32Sample"
         CCDC.Add(averageTimer32)
         
         ' Add the base counter.
         Dim averageTimer32Base As New CounterCreationData()
         averageTimer32Base.CounterType = PerformanceCounterType.AverageBase
         averageTimer32Base.CounterName = "AverageTimer32SampleBase"
         CCDC.Add(averageTimer32Base)
         
         ' Create the category.
         PerformanceCounterCategory.Create( _
            "AverageTimer32SampleCategory", _
            "Demonstrates usage of the AverageTimer32 performance counter type", CCDC)
         
         Return True
      Else
         Console.WriteLine(("Category exists - " + _
            "AverageTimer32SampleCategory"))
         Return False
      End If
   End Function 
   
   
   Private Shared Sub CreateCounters()
      ' Create the counters.
      PC = New PerformanceCounter("AverageTimer32SampleCategory", _
            "AverageTimer32Sample", False)
      
      BPC = New PerformanceCounter("AverageTimer32SampleCategory", _
            "AverageTimer32SampleBase", False)
      
      PC.RawValue = 0
      BPC.RawValue = 0
   End Sub 
   
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim perfTime As Long = 0
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Loop for the samples.
      Dim i As Integer
      For i = 0 To 9
         
         QueryPerformanceCounter(perfTime)
         PC.RawValue = perfTime
         
         BPC.IncrementBy(10)
         
         System.Threading.Thread.Sleep(1000)
         Console.WriteLine(("Next value = " + PC.NextValue().ToString()))
         samplesList.Add(PC.NextSample())
      Next i
   End Sub 
    
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      Dim sample1 As CounterSample
      Dim sample2 As CounterSample
      For i = 0 To (samplesList.Count - 1) - 1
         ' Output the sample.
         sample1 = CType(samplesList(i), CounterSample)
         sample2 = CType(samplesList(i+1), CounterSample)
         OutputSample(sample1)
         OutputSample(sample2)
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " _
            + CounterSample.Calculate(sample1, sample2).ToString()))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " _
            + MyComputeCounterValue(sample1, sample2).ToString()))

      Next i
   End Sub
   
   
  '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
  ' PERF_AVERAGE_TIMER
  '  Description - This counter type measures the time it takes, on 
  '     average, to complete a process or operation. Counters of this
  '     type display a ratio of the total elapsed time of the sample 
  '     interval to the number of processes or operations completed
  '     during that time. This counter type measures time in ticks 
  '     of the system clock. The F variable represents the number of
  '     ticks per second. The value of F is factored into the equation
  '     so that the result can be displayed in seconds.
  '
  '  Generic type - Average
  '
  '  Formula - ((N1 - N0) / F) / (D1 - D0), where the numerator (N)
  '     represents the number of ticks counted during the last 
  '     sample interval, F represents the frequency of the ticks, 
  '     and the denominator (D) represents the number of operations
  '     completed during the last sample interval.
  '
  '  Average - ((Nx - N0) / F) / (Dx - D0)
  '
  '  Example - PhysicalDisk\ Avg. Disk sec/Transfer 
  '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
   Private Shared Function MyComputeCounterValue( _
                                    s0 As CounterSample, _
                                    s1 As CounterSample) As Single
      Dim n1 As Int64 = s1.RawValue
      Dim n0 As Int64 = s0.RawValue
      Dim f As Decimal = CType(s1.SystemFrequency, Decimal)
      Dim d1 As Int64 = s1.BaseValue
      Dim d0 As Int64 = s0.BaseValue
      
      Dim numerator As Double = System.Convert.ToDouble(n1 - n0)
      Dim denominator As Double = System.Convert.ToDouble(d1 - d0)
      Dim counterValue As Single = CType(numerator, Single)
      counterValue = counterValue / CType(f, Single)
      counterValue = counterValue / CType(denominator, Single)

      Return counterValue
   End Function 
   
   
   ' Output information about the counter sample.
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine("+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Cr _
            + ControlChars.Lf)
      Console.WriteLine(("   BaseValue        = " _
            + s.BaseValue.ToString()))
      Console.WriteLine(("   CounterFrequency = " + _
            s.CounterFrequency.ToString()))
      Console.WriteLine(("   CounterTimeStamp = " + _
            s.CounterTimeStamp.ToString()))
      Console.WriteLine(("   CounterType      = " + _
            s.CounterType.ToString()))
      Console.WriteLine(("   RawValue         = " + _
            s.RawValue.ToString()))
      Console.WriteLine(("   SystemFrequency  = " + _
            s.SystemFrequency.ToString()))
      Console.WriteLine(("   TimeStamp        = " + _
            s.TimeStamp.ToString()))
      Console.WriteLine(("   TimeStamp100nSec = " + _
            s.TimeStamp100nSec.ToString()))
      Console.WriteLine("++++++++++++++++++++++")
   End Sub
   
   <DllImport("Kernel32.dll")>  _
   Public Shared Function _
        QueryPerformanceCounter(ByRef value As Long) As Boolean
   End Function

End Class


[C#] 

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime.InteropServices;
            
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("AverageTimer32SampleCategory") ) 
        {

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageTimer32 = new CounterCreationData();
            averageTimer32.CounterType = PerformanceCounterType.AverageTimer32;
            averageTimer32.CounterName = "AverageTimer32Sample";
            CCDC.Add(averageTimer32);
            
            // Add the base counter.
            CounterCreationData averageTimer32Base = new CounterCreationData();
            averageTimer32Base.CounterType = PerformanceCounterType.AverageBase;
            averageTimer32Base.CounterName = "AverageTimer32SampleBase";
            CCDC.Add(averageTimer32Base);

            // Create the category.
            PerformanceCounterCategory.Create("AverageTimer32SampleCategory", 
                "Demonstrates usage of the AverageTimer32 performance counter type", 
                CCDC);
                
            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - " + "AverageTimer32SampleCategory");
            return(false);
        }
    }
    
    private static void CreateCounters()
    {
        // Create the counters.
        PC = new PerformanceCounter("AverageTimer32SampleCategory", 
            "AverageTimer32Sample", 
            false);
            
        BPC = new PerformanceCounter("AverageTimer32SampleCategory", 
            "AverageTimer32SampleBase", 
            false);
            
        PC.RawValue = 0;
        BPC.RawValue = 0;
    }
    

    private static void CollectSamples(ArrayList samplesList)
    {
        
        long perfTime = 0;
        Random r = new Random( DateTime.Now.Millisecond );

        // Loop for the samples.
        for (int i = 0; i < 10; i++) {
            
            QueryPerformanceCounter(out perfTime);
            PC.RawValue = perfTime;
            
            BPC.IncrementBy(10);

            System.Threading.Thread.Sleep(1000);
            Console.WriteLine("Next value = " + PC.NextValue().ToString());
            samplesList.Add(PC.NextSample());
        }

    }
    
    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 = " + 
                CounterSample.Calculate((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]) );

        }
    }
    
    

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
    // PERF_AVERAGE_TIMER
    //  Description - This counter type measures the time it takes, on 
    //     average, to complete a process or operation. Counters of this
    //     type display a ratio of the total elapsed time of the sample 
    //     interval to the number of processes or operations completed
    //     during that time. This counter type measures time in ticks 
    //     of the system clock. The F variable represents the number of
    //     ticks per second. The value of F is factored into the equation
    //     so that the result can be displayed in seconds.
    //    
    //  Generic type - Average
    //    
    //  Formula - ((N1 - N0) / F) / (D1 - D0), where the numerator (N)
    //     represents the number of ticks counted during the last 
    //     sample interval, F represents the frequency of the ticks, 
    //     and the denominator (D) represents the number of operations
    //     completed during the last sample interval.
    //    
    //  Average - ((Nx - N0) / F) / (Dx - D0)
    //    
    //  Example - PhysicalDisk\ Avg. Disk sec/Transfer 
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Int64 n1 = s1.RawValue;
        Int64 n0 = s0.RawValue;
        ulong f = (ulong)s1.SystemFrequency;
        Int64 d1 = s1.BaseValue;
        Int64 d0 = s0.BaseValue;

        double numerator = (double)(n1 - n0);
        double denominator = (double)(d1 - d0);
        Single counterValue = (Single)(( numerator / f ) / denominator);
        return(counterValue);
    }
    
    // Output information about the counter sample.
    private static void OutputSample(CounterSample s)
    {
        Console.WriteLine("+++++++++++");
        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("++++++++++++++++++++++");
    }
    

    [DllImport("Kernel32.dll")]
    public static extern bool QueryPerformanceCounter(out long value);

}


[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
// PERF_AVERAGE_TIMER
//  Description - This counter type measures the time it takes, on 
//     average, to complete a process or operation. Counters of this
//     type display a ratio of the total elapsed time of the sample 
//     interval to the number of processes or operations completed
//     during that time. This counter type measures time in ticks 
//     of the system clock. The F variable represents the number of
//     ticks per second. The value of F is factored into the equation
//     so that the result can be displayed in seconds.
//    
//  Generic type - Average
//    
//  Formula - ((N1 - N0) / F) / (D1 - D0), where the numerator (N)
//     represents the number of ticks counted during the last 
//     sample interval, F represents the frequency of the ticks, 
//     and the denominator (D) represents the number of operations
//     completed during the last sample interval.
//    
//  Average - ((Nx - N0) / F) / (Dx - D0)
//    
//  Example - PhysicalDisk\ Avg. Disk sec/Transfer 
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//+++++++
float MyComputeCounterValue(CounterSample s0, CounterSample s1) {
    __int64 n1 = s1.RawValue;
    __int64 n0 = s0.RawValue;
    unsigned __int64 f = s1.SystemFrequency;
    __int64 d1 = s1.BaseValue;
    __int64 d0 = s0.BaseValue;

    double numerator = (double)(n1 - n0);
    double denomenator = (double)(d1 - d0);
    float counterValue = (float)(( numerator / f ) / denomenator);
    return counterValue;
}

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

[DllImport(S"Kernel32.dll")]
extern bool QueryPerformanceCounter([Out] __int64* value);

bool SetupCategory() {
    if (!PerformanceCounterCategory::Exists(S"AverageTimer32SampleCategory")) {

        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* averageTimer32 = new CounterCreationData();
        averageTimer32->CounterType = PerformanceCounterType::AverageTimer32;
        averageTimer32->CounterName = S"AverageTimer32Sample";
        CCDC->Add(averageTimer32);

        // Add the base counter.
        CounterCreationData* averageTimer32Base = new CounterCreationData();
        averageTimer32Base->CounterType = PerformanceCounterType::AverageBase;
        averageTimer32Base->CounterName = S"AverageTimer32SampleBase";
        CCDC->Add(averageTimer32Base);

        // Create the category.
        PerformanceCounterCategory::Create(S"AverageTimer32SampleCategory", 
            S"Demonstrates usage of the AverageTimer32 performance counter type", 
            CCDC);

        return(true);
    } else {
        Console::WriteLine(S"Category exists - AverageTimer32SampleCategory");
        return(false);
    }
}

void CreateCounters(PerformanceCounter*& PC, PerformanceCounter*& BPC) {
    // Create the counters.
    PC = new PerformanceCounter(S"AverageTimer32SampleCategory", 
        S"AverageTimer32Sample", false);
    BPC = new PerformanceCounter(S"AverageTimer32SampleCategory", 
        S"AverageTimer32SampleBase", false);

    PC->RawValue = 0;
    BPC->RawValue = 0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC, PerformanceCounter* BPC) {
    __int64 perfTime = 0;
    Random* r = new Random(DateTime::Now.Millisecond);

    // Loop for the samples.
    for (int i = 0; i < 10; i++) {
        QueryPerformanceCounter(&perfTime);
        PC->RawValue = perfTime;
        BPC->IncrementBy(10);

        System::Threading::Thread::Sleep(1000);
        Console::WriteLine(S"Next value = {0}", __box(PC->NextValue()));
        samplesList->Add(__box(PC->NextSample()));
    }
}

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

        // Use .NET to calculate the counter value.
        Console::WriteLine(S".NET computed counter value = {0}", 
            __box(CounterSample::Calculate(*__try_cast<__box CounterSample*>(samplesList->Item[i]),
            *__try_cast<__box CounterSample*>(samplesList->Item[i+1]))));

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

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;
    PerformanceCounter* BPC;

    SetupCategory();
    CreateCounters(PC, BPC);
    CollectSamples(samplesList, PC, BPC);
    CalculateResults(samplesList);
}

[Visual Basic, C#, C++] ElapsedTime

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic

Public Class App
   Private Shared PC As PerformanceCounter
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
   End Sub
  
   
   Private Shared Function SetupCategory() As Boolean
      If Not PerformanceCounterCategory.Exists("ElapsedTimeSampleCategory") Then
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim ETimeData As New CounterCreationData()
         ETimeData.CounterType = PerformanceCounterType.ElapsedTime
         ETimeData.CounterName = "ElapsedTimeSample"
         CCDC.Add(ETimeData)
         
         ' Create the category.
         PerformanceCounterCategory.Create("ElapsedTimeSampleCategory", _
            "Demonstrates usage of the ElapsedTime performance counter type.", CCDC)
         
         Return True
      Else
         Console.WriteLine("Category exists - ElapsedTimeSampleCategory")
         Return False
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counter.
      PC = New PerformanceCounter("ElapsedTimeSampleCategory", _
            "ElapsedTimeSample", False)
   End Sub 'CreateCounters
   
   
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim pcValue As Long
      Dim Start As DateTime
      
      ' Initialize the counter.
      QueryPerformanceCounter(pcValue)
      PC.RawValue = pcValue
      Start = DateTime.Now
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 999
         ' Output the values.
         If j Mod 10 = 9 Then
            Console.WriteLine(("NextValue() = " _
                + PC.NextValue().ToString()))
            Console.WriteLine(("Actual elapsed time = " _
                + DateTime.Now.Subtract(Start).ToString()))
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         End If
         
         ' reset the counter on 100th iteration.
         If j Mod 100 = 0 Then
            QueryPerformanceCounter(pcValue)
            PC.RawValue = pcValue
            Start = DateTime.Now
         End If
         System.Threading.Thread.Sleep(50)
      Next j
      
      Console.WriteLine(("Elapsed time = " + _
            DateTime.Now.Subtract(Start).ToString()))
   End Sub 
   
   
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++")

      Console.WriteLine("Sample values - " + ControlChars.Cr _
            + ControlChars.Lf)
      Console.WriteLine(("   BaseValue        = " _
            + s.BaseValue.ToString()))
      Console.WriteLine(("   CounterFrequency = " + _
            s.CounterFrequency.ToString()))
      Console.WriteLine(("   CounterTimeStamp = " + _
            s.CounterTimeStamp.ToString()))
      Console.WriteLine(("   CounterType      = " + _
            s.CounterType.ToString()))
      Console.WriteLine(("   RawValue         = " + _
            s.RawValue.ToString()))
      Console.WriteLine(("   SystemFrequency  = " + _
            s.SystemFrequency.ToString()))
      Console.WriteLine(("   TimeStamp        = " + _
            s.TimeStamp.ToString()))
      Console.WriteLine(("   TimeStamp100nSec = " + _
            s.TimeStamp100nSec.ToString()))
      
      Console.WriteLine("+++++++")
   End Sub
   
   ' Reads the counter information to enable setting the RawValue.
   <DllImport("Kernel32.dll")>  _
   Public Shared Function _
        QueryPerformanceCounter(ByRef value As Long) As Boolean
   End Function
End Class

[C#] 
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime.InteropServices;

public class App 
{
    private static PerformanceCounter PC;


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

        SetupCategory();
        CreateCounters();
        CollectSamples(samplesList);
    }


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

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData ETimeData = new CounterCreationData();
            ETimeData.CounterType = PerformanceCounterType.ElapsedTime;
            ETimeData.CounterName = "ElapsedTimeSample";
            CCDC.Add(ETimeData);       
        
            // Create the category.
            PerformanceCounterCategory.Create("ElapsedTimeSampleCategory", 
                "Demonstrates usage of the ElapsedTime performance counter type.",    
                CCDC);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - ElapsedTimeSampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counter.
        PC = new PerformanceCounter("ElapsedTimeSampleCategory", 
            "ElapsedTimeSample", 
            false);
  
    }

    private static void CollectSamples(ArrayList samplesList)
    {
    
        long pcValue;
        DateTime Start;

        // Initialize the counter.
        QueryPerformanceCounter(out pcValue);
        PC.RawValue = pcValue;
        Start = DateTime.Now;

        // Loop for the samples.
        for (int j = 0; j < 1000; j++) 
        {
            // Output the values.
            if ((j % 10) == 9) 
            {
                Console.WriteLine("NextValue() = " + PC.NextValue().ToString());
                Console.WriteLine("Actual elapsed time = " + DateTime.Now.Subtract(Start).ToString());
                OutputSample(PC.NextSample());
                samplesList.Add( PC.NextSample() );
            }

            // Reset the counter on 100th iteration.
            if (j % 100 == 0)
            {
                QueryPerformanceCounter(out pcValue);
                PC.RawValue = pcValue;
                Start = DateTime.Now;
            }
            System.Threading.Thread.Sleep(50);
        }

        Console.WriteLine("Elapsed time = " + DateTime.Now.Subtract(Start).ToString());
    }

    
    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("++++++++++++++++++++++");
    }


    // Reads the counter information to enable setting the RawValue.
    [DllImport("Kernel32.dll")]
    public static extern bool QueryPerformanceCounter(out long value);
}

[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

void OutputSample(CounterSample s) {
    Console::WriteLine(S"\r\n+++++++++++");
    Console::WriteLine(S"Sample values - \r\n");
    Console::WriteLine(S"   BaseValue        = {0}", __box(s.BaseValue));
    Console::WriteLine(S"   CounterFrequency = {0}", __box(s.CounterFrequency));
    Console::WriteLine(S"   CounterTimeStamp = {0}", __box(s.CounterTimeStamp));
    Console::WriteLine(S"   CounterType      = {0}", __box(s.CounterType));
    Console::WriteLine(S"   RawValue         = {0}", __box(s.RawValue));
    Console::WriteLine(S"   SystemFrequency  = {0}", __box(s.SystemFrequency));
    Console::WriteLine(S"   TimeStamp        = {0}", __box(s.TimeStamp));
    Console::WriteLine(S"   TimeStamp100nSec = {0}", __box(s.TimeStamp100nSec));
    Console::WriteLine(S"++++++++++++++++++++++");
}


// Reads the counter information to enable setting the RawValue.
[DllImport(S"Kernel32.dll")]
extern bool QueryPerformanceCounter([Out] __int64* value);

bool SetupCategory() {
    if (!PerformanceCounterCategory::Exists(S"ElapsedTimeSampleCategory")) {

        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* ETimeData = new CounterCreationData();
        ETimeData->CounterType = PerformanceCounterType::ElapsedTime;
        ETimeData->CounterName = S"ElapsedTimeSample";
        CCDC->Add(ETimeData);            

        // Create the category.
        PerformanceCounterCategory::Create(S"ElapsedTimeSampleCategory", 
            S"Demonstrates usage of the ElapsedTime performance counter type.",    
            CCDC);
        return true;
    } else {
        Console::WriteLine(S"Category exists - ElapsedTimeSampleCategory");
        return false;
    }
}

void CreateCounters(PerformanceCounter*& PC) {
    // Create the counter.
    PC = new PerformanceCounter(S"ElapsedTimeSampleCategory", 
        S"ElapsedTimeSample", false);
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC) {
    __int64 pcValue;
    DateTime Start;

    // Initialize the counter.
    QueryPerformanceCounter(&pcValue);
    PC->RawValue = pcValue;
    Start = DateTime::Now;

    // Loop for the samples.
    for (int j = 0; j < 1000; j++) {
        // Output the values.
        if ((j % 10) == 9) {
            Console::WriteLine(S"NextValue() = {0}", __box(PC->NextValue()));
            Console::WriteLine(S"Actual elapsed time = {0}", __box(DateTime::Now.Subtract(Start)));
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        }

        // reset the counter on 100th iteration.
        if (j % 100 == 0) {
            QueryPerformanceCounter(&pcValue);
            PC->RawValue = pcValue;
            Start = DateTime::Now;
        }
        System::Threading::Thread::Sleep(50);
    }

    Console::WriteLine(S"Elapsed time = {0}", __box(DateTime::Now.Subtract(Start)));
}

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;

    SetupCategory();
    CreateCounters(PC);
    CollectSamples(samplesList, PC);
}

[Visual Basic, C#, C++] NumberOfItems32

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class NumberOfItems64
   
   Private Shared PC As PerformanceCounter
   
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 'Main
   
   
   Private Shared Function SetupCategory() As Boolean
      If Not PerformanceCounterCategory.Exists("NumberOfItems32SampleCategory") Then
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim NOI64 As New CounterCreationData()
         NOI64.CounterType = PerformanceCounterType.NumberOfItems64
         NOI64.CounterName = "NumberOfItems32Sample"
         CCDC.Add(NOI64)
         
         ' Create the category.
         PerformanceCounterCategory.Create("NumberOfItems32SampleCategory", "Demonstrates usage of the NumberOfItems32 performance counter type.", CCDC)
         
         Return True
      Else
         Console.WriteLine("Category exists - NumberOfItems32SampleCategory")
         Return False
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counter.
      PC = New PerformanceCounter("NumberOfItems32SampleCategory", "NumberOfItems32Sample", False)
      
      PC.RawValue = 0
   End Sub 'CreateCounters
    
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      
      
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         
         Dim value As Integer = r.Next(1, 10)
         Console.Write((j + " = " + value))
         
         PC.IncrementBy(value)
         
         If j Mod 10 = 9 Then
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         Else
            Console.WriteLine()
         End If 
         System.Threading.Thread.Sleep(50)
      Next j
   End Sub 'CollectSamples
    
   
   
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      For i = 0 To (samplesList.Count - 1) - 1
         ' Output the sample.
         OutputSample(CType(samplesList(i), CounterSample))
         OutputSample(CType(samplesList((i + 1)), CounterSample))
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
      Next i
   End Sub 'CalculateResults
   
   
   
   
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   Private Shared Function MyComputeCounterValue(s0 As CounterSample, s1 As CounterSample) As [Single]
      Dim counterValue As [Single] = s1.RawValue
      Return counterValue
   End Function 'MyComputeCounterValue
   
   
   ' Output information about the counter sample.
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
      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("++++++++++++++++++++++")
   End Sub 'OutputSample
End Class 'NumberOfItems64 



[C#] 
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class NumberOfItems64
{

    private static PerformanceCounter PC;

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

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

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

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData NOI64 = new CounterCreationData();
            NOI64.CounterType = PerformanceCounterType.NumberOfItems64;
            NOI64.CounterName = "NumberOfItems32Sample";
            CCDC.Add(NOI64);

            // Create the category.
            PerformanceCounterCategory.Create("NumberOfItems32SampleCategory", 
                "Demonstrates usage of the NumberOfItems32 performance counter type.", 
                CCDC);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - NumberOfItems32SampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counter.
        PC = new PerformanceCounter("NumberOfItems32SampleCategory", 
            "NumberOfItems32Sample", 
            false);

        PC.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);

            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]) );

        }
    }
    

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Single counterValue = s1.RawValue;
        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("++++++++++++++++++++++");
    }


    
}

[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

float MyComputeCounterValue(CounterSample s0, CounterSample s1) {
    float counterValue = (float)s1.RawValue;
    return counterValue;
}

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

bool SetupCategory() {        
    if (!PerformanceCounterCategory::Exists(S"NumberOfItems32SampleCategory")) {

        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* NOI64 = new CounterCreationData();
        NOI64->CounterType = PerformanceCounterType::NumberOfItems64;
        NOI64->CounterName = S"NumberOfItems32Sample";
        CCDC->Add(NOI64);

        // Create the category.
        PerformanceCounterCategory::Create(S"NumberOfItems32SampleCategory", 
            S"Demonstrates usage of the NumberOfItems32 performance counter type.", 
            CCDC);
        return true;
    } else {
        Console::WriteLine(S"Category exists - NumberOfItems32SampleCategory");
        return false;
    }
}

void CreateCounters(PerformanceCounter*& PC) {
    // Create the counter.
    PC = new PerformanceCounter(S"NumberOfItems32SampleCategory", 
        S"NumberOfItems32Sample", false);

    PC->RawValue=0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC) {
    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(S"{0} = {1}", __box(j), __box(value));

        PC->IncrementBy(value);

        if ((j % 10) == 9) {
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        } else
            Console::WriteLine();

        System::Threading::Thread::Sleep(50);
    }
}

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

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

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

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;

    SetupCategory();
    CreateCounters(PC);
    CollectSamples(samplesList, PC);
    CalculateResults(samplesList);
}

[Visual Basic, C#, C++] NumberOfItems64

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class NumberOfItems64
   
   Private Shared PC As PerformanceCounter
   
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 'Main
   
   
   Private Shared Function SetupCategory() As Boolean
      If Not PerformanceCounterCategory.Exists("NumberOfItems64SampleCategory") Then
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim NOI64 As New CounterCreationData()
         NOI64.CounterType = PerformanceCounterType.NumberOfItems64
         NOI64.CounterName = "NumberOfItems64Sample"
         CCDC.Add(NOI64)
         
         ' Create the category.
         PerformanceCounterCategory.Create("NumberOfItems64SampleCategory", "Demonstrates usage of the NumberOfItems64 performance counter type.", CCDC)
         
         Return True
      Else
         Console.WriteLine("Category exists - NumberOfItems64SampleCategory")
         Return False
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counters.
      PC = New PerformanceCounter("NumberOfItems64SampleCategory", "NumberOfItems64Sample", False)
      
      PC.RawValue = 0
   End Sub 'CreateCounters
    
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         
         Dim value As Integer = r.Next(1, 10)
         Console.Write((j + " = " + value))
         
         PC.IncrementBy(value)
         
         If j Mod 10 = 9 Then
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         Else
            Console.WriteLine()
         End If 
         System.Threading.Thread.Sleep(50)
      Next j
   End Sub 'CollectSamples
    
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      For i = 0 To (samplesList.Count - 1) - 1
         ' Output the sample.
         OutputSample(CType(samplesList(i), CounterSample))
         OutputSample(CType(samplesList((i + 1)), CounterSample))
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
      Next i
   End Sub 'CalculateResults
   
   
   
   
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   Private Shared Function MyComputeCounterValue(s0 As CounterSample, s1 As CounterSample) As [Single]
      Dim counterValue As [Single] = s1.RawValue
      Return counterValue
   End Function 'MyComputeCounterValue
   
   
   ' Output information about the counter sample.
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
      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("++++++++++++++++++++++")
   End Sub 'OutputSample
End Class 'NumberOfItems64 

[C#] 
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class NumberOfItems64
{

    private static PerformanceCounter PC;

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

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

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

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData NOI64 = new CounterCreationData();
            NOI64.CounterType = PerformanceCounterType.NumberOfItems64;
            NOI64.CounterName = "NumberOfItems64Sample";
            CCDC.Add(NOI64);

            // Create the category.
            PerformanceCounterCategory.Create("NumberOfItems64SampleCategory", 
                "Demonstrates usage of the NumberOfItems64 performance counter type.", 
                CCDC);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - NumberOfItems64SampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counters.
        PC = new PerformanceCounter("NumberOfItems64SampleCategory", 
            "NumberOfItems64Sample", 
            false);

        PC.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);

            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]) );

        }
    }

    
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Single counterValue = s1.RawValue;
        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("++++++++++++++++++++++");
    }

}

[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

float MyComputeCounterValue(CounterSample s0, CounterSample s1) {
    float counterValue = (float)s1.RawValue;
    return counterValue;
}

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

bool SetupCategory() {        
    if (!PerformanceCounterCategory::Exists(S"NumberOfItems64SampleCategory")) {

        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* NOI64 = new CounterCreationData();
        NOI64->CounterType = PerformanceCounterType::NumberOfItems64;
        NOI64->CounterName = S"NumberOfItems64Sample";
        CCDC->Add(NOI64);

        // Create the category.
        PerformanceCounterCategory::Create(S"NumberOfItems64SampleCategory", 
            S"Demonstrates usage of the NumberOfItems64 performance counter type.", 
            CCDC);

        return true;
    } else {
        Console::WriteLine(S"Category exists - NumberOfItems64SampleCategory");
        return false;
    }
}

void CreateCounters(PerformanceCounter*& PC) {
    // Create the counters.
    PC = new PerformanceCounter(S"NumberOfItems64SampleCategory", 
        S"NumberOfItems64Sample", false);

    PC->RawValue=0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC) {
    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(S"{0} = {1}", __box(j), __box(value));

        PC->IncrementBy(value);

        if ((j % 10) == 9) {
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        } else
            Console::WriteLine();

        System::Threading::Thread::Sleep(50);
    }
}

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

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

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

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;

    SetupCategory();
    CreateCounters(PC);
    CollectSamples(samplesList, PC);
    CalculateResults(samplesList);
}

[Visual Basic, C#, C++] RateOfCountsPerSecond32

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class App
   Private Shared PC As PerformanceCounter
   
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 'Main
   
   
   Private Shared Function SetupCategory() As Boolean
      
      If Not PerformanceCounterCategory.Exists("RateOfCountsPerSecond32SampleCategory") Then
         
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim rateOfCounts32 As New CounterCreationData()
         rateOfCounts32.CounterType = PerformanceCounterType.RateOfCountsPerSecond32
         rateOfCounts32.CounterName = "RateOfCountsPerSecond32Sample"
         CCDC.Add(rateOfCounts32)
         
         ' Create the category.
         PerformanceCounterCategory.Create("RateOfCountsPerSecond32SampleCategory", "Demonstrates usage of the RateOfCountsPerSecond32 performance counter type.", CCDC)
         Return True
      Else
         Console.WriteLine("Category exists - RateOfCountsPerSecond32SampleCategory")
         Return False
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counter.
      PC = New PerformanceCounter("RateOfCountsPerSecond32SampleCategory", "RateOfCountsPerSecond32Sample", False)
      
      PC.RawValue = 0
   End Sub 'CreateCounters
    
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Initialize the performance counter.
      PC.NextSample()
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         
         Dim value As Integer = r.Next(1, 10)
         PC.IncrementBy(value)
         Console.Write((j + " = " + value))
         
         If j Mod 10 = 9 Then
            Console.WriteLine((";       NextValue() = " + PC.NextValue().ToString()))
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         Else
            Console.WriteLine()
         End If 
         System.Threading.Thread.Sleep(50)
      Next j
   End Sub 'CollectSamples
   
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      For i = 0 To (samplesList.Count - 1) - 1
         ' Output the sample.
         OutputSample(CType(samplesList(i), CounterSample))
         OutputSample(CType(samplesList((i + 1)), CounterSample))
         
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
      Next i
   End Sub 'CalculateResults
   
   
   
   
   
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   '    PERF_COUNTER_COUNTER
   '    Description     - This counter type shows the average number of operations completed
   '        during each second of the sample interval. Counters of this type
   '        measure time in ticks of the system clock. The F variable represents
   '        the number of ticks per second. The value of F is factored into the
   '        equation so that the result can be displayed in seconds.
   '
   '    Generic type - Difference
   '
   '    Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
   '        of operations performed during the last sample interval, the denominator
   '        (D) represents the number of ticks elapsed during the last sample
   '        interval, and F is the frequency of the ticks.
   '
   '         Average - (Nx - N0) / ((Dx - D0) / F) 
   '
   '       Example - System\ File Read Operations/sec 
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   Private Shared Function MyComputeCounterValue(s0 As CounterSample, s1 As CounterSample) As [Single]
      Dim numerator As [Single] = CType(s1.RawValue - s0.RawValue, [Single])
      Dim denomenator As [Single] = CType(s1.TimeStamp - s0.TimeStamp, [Single]) / CType(s1.SystemFrequency, [Single])
      Dim counterValue As [Single] = numerator / denomenator
      Return counterValue
   End Function 'MyComputeCounterValue
   
   
   ' Output information about the counter sample.
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
      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("++++++++++++++++++++++")
   End Sub 'OutputSample
End Class 'App 


[C#] 
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class App 
{
    private static PerformanceCounter PC;

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

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

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


            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData rateOfCounts32 = new CounterCreationData();
            rateOfCounts32.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
            rateOfCounts32.CounterName = "RateOfCountsPerSecond32Sample";
            CCDC.Add(rateOfCounts32);
            
             // Create the category.
            PerformanceCounterCategory.Create("RateOfCountsPerSecond32SampleCategory", 
                "Demonstrates usage of the RateOfCountsPerSecond32 performance counter type.", 
                CCDC);
            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - RateOfCountsPerSecond32SampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counter.
        PC = new PerformanceCounter("RateOfCountsPerSecond32SampleCategory", 
            "RateOfCountsPerSecond32Sample", 
            false);

        PC.RawValue=0;
        
    }

    private static void CollectSamples(ArrayList samplesList)
    {
    
        Random r = new Random( DateTime.Now.Millisecond );

        // Initialize the performance counter.
        PC.NextSample();

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

            if ((j % 10) == 9) 
            {
                Console.WriteLine(";       NextValue() = " + PC.NextValue().ToString());
                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]) );


        }
    }


    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //    PERF_COUNTER_COUNTER
    //    Description     - This counter type shows the average number of operations completed
    //        during each second of the sample interval. Counters of this type
    //        measure time in ticks of the system clock. The F variable represents
    //        the number of ticks per second. The value of F is factored into the
    //        equation so that the result can be displayed in seconds.
    //
    //    Generic type - Difference
    //
    //    Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
    //        of operations performed during the last sample interval, the denominator
    //        (D) represents the number of ticks elapsed during the last sample
    //        interval, and F is the frequency of the ticks.
    //
    //         Average - (Nx - N0) / ((Dx - D0) / F) 
    //
    //       Example - System\ File Read Operations/sec 
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Single numerator = (Single)(s1.RawValue - s0.RawValue);
        Single denomenator = (Single)(s1.TimeStamp - s0.TimeStamp) / (Single)s1.SystemFrequency;
        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("++++++++++++++++++++++");
    }

}


[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//    PERF_COUNTER_COUNTER
//    Description     - This counter type shows the average number of operations completed
//        during each second of the sample interval. Counters of this type
//        measure time in ticks of the system clock. The F variable represents
//        the number of ticks per second. The value of F is factored into the
//        equation so that the result can be displayed in seconds.
//
//    Generic type - Difference
//
//    Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
//        of operations performed during the last sample interval, the denominator
//        (D) represents the number of ticks elapsed during the last sample
//        interval, and F is the frequency of the ticks.
//
//         Average - (Nx - N0) / ((Dx - D0) / F) 
//
//       Example - System\ File Read Operations/sec 
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
float MyComputeCounterValue(CounterSample s0, CounterSample s1) {
    float numerator = (float)(s1.RawValue - s0.RawValue);
    float denomenator = (float)(s1.TimeStamp - s0.TimeStamp) / (float)s1.SystemFrequency;
    float counterValue = numerator / denomenator;
    return counterValue;
}

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

bool SetupCategory() {
    if (!PerformanceCounterCategory::Exists(S"RateOfCountsPerSecond32SampleCategory")) {

        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* rateOfCounts32 = new CounterCreationData();
        rateOfCounts32->CounterType = PerformanceCounterType::RateOfCountsPerSecond32;
        rateOfCounts32->CounterName = S"RateOfCountsPerSecond32Sample";
        CCDC->Add(rateOfCounts32);

        // Create the category.
        PerformanceCounterCategory::Create(S"RateOfCountsPerSecond32SampleCategory", 
            S"Demonstrates usage of the RateOfCountsPerSecond32 performance counter type.", 
            CCDC);
        return true;
    } else {
        Console::WriteLine(S"Category exists - RateOfCountsPerSecond32SampleCategory");
        return false;
    }
}

void CreateCounters(PerformanceCounter*& PC) {
    // Create the counter.
    PC = new PerformanceCounter(S"RateOfCountsPerSecond32SampleCategory", 
        S"RateOfCountsPerSecond32Sample", false);

    PC->RawValue=0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC) {
    Random* r = new Random(DateTime::Now.Millisecond);

    // Initialize the performance counter.
    PC->NextSample();

    // Loop for the samples.
    for (int j = 0; j < 100; j++) {
        int value = r->Next(1, 10);
        PC->IncrementBy(value);
        Console::Write(S"{0} = {1}", __box(j), __box(value));

        if ((j % 10) == 9) {
            Console::WriteLine(S";       NextValue() = {0}", __box(PC->NextValue()));
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        } else
            Console::WriteLine();

        System::Threading::Thread::Sleep(50);
    }
}

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


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

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

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;

    SetupCategory();
    CreateCounters(PC);
    CollectSamples(samplesList, PC);
    CalculateResults(samplesList);
}

[Visual Basic, C#, C++] RateOfCountsPerSecond64

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class App
   Private Shared PC As PerformanceCounter
   
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 'Main
   
   
   Private Shared Function SetupCategory() As Boolean
      
      
      If Not PerformanceCounterCategory.Exists("RateOfCountsPerSecond64SampleCategory") Then
         
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim rateOfCounts64 As New CounterCreationData()
         rateOfCounts64.CounterType = PerformanceCounterType.RateOfCountsPerSecond64
         rateOfCounts64.CounterName = "RateOfCountsPerSecond64Sample"
         CCDC.Add(rateOfCounts64)
         
         ' Create the category.
         PerformanceCounterCategory.Create("RateOfCountsPerSecond64SampleCategory", "Demonstrates usage of the RateOfCountsPerSecond64 performance counter type.", CCDC)
         Return True
      Else
         Console.WriteLine("Category exists - RateOfCountsPerSecond64SampleCategory")
         Return False
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counter.
      PC = New PerformanceCounter("RateOfCountsPerSecond64SampleCategory", "RateOfCountsPerSecond64Sample", False)
      
      PC.RawValue = 0
   End Sub 'CreateCounters
    
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Initialize the performance counter.
      PC.NextSample()
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         
         Dim value As Integer = r.Next(1, 10)
         PC.IncrementBy(value)
         Console.Write((j + " = " + value))
         
         If j Mod 10 = 9 Then
            Console.WriteLine((";       NextValue() = " + PC.NextValue().ToString()))
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         Else
            Console.WriteLine()
         End If 
         System.Threading.Thread.Sleep(50)
      Next j
   End Sub 'CollectSamples
    
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      For i = 0 To (samplesList.Count - 1) - 1
         ' Output the sample.
         OutputSample(CType(samplesList(i), CounterSample))
         OutputSample(CType(samplesList((i + 1)), CounterSample))
         
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample))))
      Next i
   End Sub 'CalculateResults
   
   
   
   
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   '    PERF_COUNTER_COUNTER
   '    Description     - This counter type shows the average number of operations completed
   '        during each second of the sample interval. Counters of this type
   '        measure time in ticks of the system clock. The F variable represents
   '        the number of ticks per second. The value of F is factored into the
   '        equation so that the result can be displayed in seconds.
   '
   '    Generic type - Difference
   '
   '    Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
   '        of operations performed during the last sample interval, the denominator
   '        (D) represents the number of ticks elapsed during the last sample
   '        interval, and F is the frequency of the ticks.
   '
   '    Average - (Nx - N0) / ((Dx - D0) / F) 
   '
   '  Example - System\ File Read Operations/sec 
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   Private Shared Function MyComputeCounterValue(s0 As CounterSample, s1 As CounterSample) As [Single]
      Dim numerator As [Single] = CType(s1.RawValue - s0.RawValue, [Single])
      Dim denomenator As [Single] = CType(s1.TimeStamp - s0.TimeStamp, [Single]) / CType(s1.SystemFrequency, [Single])
      Dim counterValue As [Single] = numerator / denomenator
      Return counterValue
   End Function 'MyComputeCounterValue
   
   
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
      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("++++++++++++++++++++++")
   End Sub 'OutputSample
End Class 'App


[C#] 
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class App 
{
    private static PerformanceCounter PC;

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

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

    private static bool SetupCategory()
    {


        if ( !PerformanceCounterCategory.Exists("RateOfCountsPerSecond64SampleCategory") ) 
        {


            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData rateOfCounts64 = new CounterCreationData();
            rateOfCounts64.CounterType = PerformanceCounterType.RateOfCountsPerSecond64;
            rateOfCounts64.CounterName = "RateOfCountsPerSecond64Sample";
            CCDC.Add(rateOfCounts64);
            
            // Create the category.
            PerformanceCounterCategory.Create("RateOfCountsPerSecond64SampleCategory", 
                "Demonstrates usage of the RateOfCountsPerSecond64 performance counter type.", 
                CCDC);
            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - RateOfCountsPerSecond64SampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counter.
        PC = new PerformanceCounter("RateOfCountsPerSecond64SampleCategory", 
            "RateOfCountsPerSecond64Sample", 
            false);

        PC.RawValue=0;
        
    }

    private static void CollectSamples(ArrayList samplesList)
    {

        Random r = new Random( DateTime.Now.Millisecond );

        // Initialize the performance counter.
        PC.NextSample();

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

            if ((j % 10) == 9) 
            {
                Console.WriteLine(";       NextValue() = " + PC.NextValue().ToString());
                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]) );


        }
    }

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //    PERF_COUNTER_COUNTER
    //    Description     - This counter type shows the average number of operations completed
    //        during each second of the sample interval. Counters of this type
    //        measure time in ticks of the system clock. The F variable represents
    //        the number of ticks per second. The value of F is factored into the
    //        equation so that the result can be displayed in seconds.
    //
    //    Generic type - Difference
    //
    //    Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
    //        of operations performed during the last sample interval, the denominator
    //        (D) represents the number of ticks elapsed during the last sample
    //        interval, and F is the frequency of the ticks.
    //
    //    Average - (Nx - N0) / ((Dx - D0) / F) 
    //
    //  Example - System\ File Read Operations/sec 
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Single numerator = (Single)(s1.RawValue - s0.RawValue);
        Single denomenator = (Single)(s1.TimeStamp - s0.TimeStamp) / (Single)s1.SystemFrequency;
        Single counterValue = numerator / denomenator;
        return(counterValue);
    }
    
    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("++++++++++++++++++++++");
    }
}


[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//    PERF_COUNTER_COUNTER
//    Description     - This counter type shows the average number of operations completed
//        during each second of the sample interval. Counters of this type
//        measure time in ticks of the system clock. The F variable represents
//        the number of ticks per second. The value of F is factored into the
//        equation so that the result can be displayed in seconds.
//
//    Generic type - Difference
//
//    Formula - (N1 - N0) / ( (D1 - D0) / F), where the numerator (N) represents the number
//        of operations performed during the last sample interval, the denominator
//        (D) represents the number of ticks elapsed during the last sample
//        interval, and F is the frequency of the ticks.
//
//    Average - (Nx - N0) / ((Dx - D0) / F) 
//
//  Example - System\ File Read Operations/sec 
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
float MyComputeCounterValue(CounterSample s0, CounterSample s1) {
    float numerator = (float)(s1.RawValue - s0.RawValue);
    float denomenator = (float)(s1.TimeStamp - s0.TimeStamp) / (float)s1.SystemFrequency;
    float counterValue = numerator / denomenator;
    return counterValue;
}

void OutputSample(CounterSample s) {
    Console::WriteLine(S"\r\n+++++++++++");
    Console::WriteLine(S"Sample values - \r\n");
    Console::WriteLine(S"   BaseValue        = {0}", __box(s.BaseValue));
    Console::WriteLine(S"   CounterFrequency = {0}", __box(s.CounterFrequency));
    Console::WriteLine(S"   CounterTimeStamp = {0}", __box(s.CounterTimeStamp));
    Console::WriteLine(S"   CounterType      = {0}", __box(s.CounterType));
    Console::WriteLine(S"   RawValue         = {0}", __box(s.RawValue));
    Console::WriteLine(S"   SystemFrequency  = {0}", __box(s.SystemFrequency));
    Console::WriteLine(S"   TimeStamp        = {0}", __box(s.TimeStamp));
    Console::WriteLine(S"   TimeStamp100nSec = {0}", __box(s.TimeStamp100nSec));
    Console::WriteLine(S"++++++++++++++++++++++");
}

bool SetupCategory() {
    if (!PerformanceCounterCategory::Exists(S"RateOfCountsPerSecond64SampleCategory")) {
        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* rateOfCounts64 = new CounterCreationData();
        rateOfCounts64->CounterType = PerformanceCounterType::RateOfCountsPerSecond64;
        rateOfCounts64->CounterName = S"RateOfCountsPerSecond64Sample";
        CCDC->Add(rateOfCounts64);

        // Create the category.
        PerformanceCounterCategory::Create(S"RateOfCountsPerSecond64SampleCategory", 
            S"Demonstrates usage of the RateOfCountsPerSecond64 performance counter type.", 
            CCDC);
        return true;
    } else {
        Console::WriteLine(S"Category exists - RateOfCountsPerSecond64SampleCategory");
        return false;
    }
}

void CreateCounters(PerformanceCounter*& PC) {
    // Create the counter.
    PC = new PerformanceCounter(S"RateOfCountsPerSecond64SampleCategory", 
        S"RateOfCountsPerSecond64Sample", false);

    PC->RawValue=0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC) {
    Random* r = new Random(DateTime::Now.Millisecond);

    // Initialize the performance counter.
    PC->NextSample();

    // Loop for the samples.
    for (int j = 0; j < 100; j++) {

        int value = r->Next(1, 10);
        PC->IncrementBy(value);
        Console::Write(S"{0} = {1}", __box(j), __box(value));

        if ((j % 10) == 9) {
            Console::WriteLine(S";       NextValue() = {0}", __box(PC->NextValue()));
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        } else
            Console::WriteLine();

        System::Threading::Thread::Sleep(50);
    }
}

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


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

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

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;

    SetupCategory();
    CreateCounters(PC);
    CollectSamples(samplesList, PC);
    CalculateResults(samplesList);
}

[Visual Basic, C#, C++] RawFraction

[Visual Basic] 
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _


Public Class App
   Private Shared PC As PerformanceCounter
   Private Shared BPC As PerformanceCounter
   
   
   Public Shared Sub Main()
      Dim samplesList As New ArrayList()
      
      SetupCategory()
      CreateCounters()
      CollectSamples(samplesList)
      CalculateResults(samplesList)
   End Sub 'Main
   
   
   Private Shared Function SetupCategory() As Boolean
      
      
      If Not PerformanceCounterCategory.Exists("RawFractionSampleCategory") Then
         
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim rf As New CounterCreationData()
         rf.CounterType = PerformanceCounterType.RawFraction
         rf.CounterName = "RawFractionSample"
         CCDC.Add(rf)
         
         ' Add the base counter.
         Dim rfBase As New CounterCreationData()
         rfBase.CounterType = PerformanceCounterType.RawBase
         rfBase.CounterName = "RawFractionSampleBase"
         CCDC.Add(rfBase)
         
         ' Create the category.
         PerformanceCounterCategory.Create("RawFractionSampleCategory", "Demonstrates usage of the RawFraction performance counter type.", CCDC)
         
         Return True
      Else
         Console.WriteLine("Category exists - RawFractionSampleCategory")
         Return False
      End If
   End Function 'SetupCategory
   
   
   Private Shared Sub CreateCounters()
      ' Create the counters.
      PC = New PerformanceCounter("RawFractionSampleCategory", "RawFractionSample", False)
      
      BPC = New PerformanceCounter("RawFractionSampleCategory", "RawFractionSampleBase", False)
      
      PC.RawValue = 0
      BPC.RawValue = 0
   End Sub 'CreateCounters
   
   
   Private Shared Sub CollectSamples(samplesList As ArrayList)
      
      Dim r As New Random(DateTime.Now.Millisecond)
      
      ' Initialize the performance counter.
      PC.NextSample()
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         Dim value As Integer = r.Next(1, 10)
         Console.Write((j + " = " + value))
         
         ' Increment the base every time, because the counter measures the number 
         ' of high hits (raw fraction value) against all the hits (base value).
         BPC.Increment()
         
         ' Get the % of samples that are 9 or 10 out of all the samples taken.
         If value >= 9 Then
            PC.Increment()
         End If 
         ' Copy out the next value every ten times around the loop.
         If j Mod 10 = 9 Then
            Console.WriteLine((";       NextValue() = " + PC.NextValue().ToString()))
            OutputSample(PC.NextSample())
            samplesList.Add(PC.NextSample())
         Else
            Console.WriteLine()
         End If 
         System.Threading.Thread.Sleep(50)
      Next j
   End Sub 'CollectSamples
    
   
   
   Private Shared Sub CalculateResults(samplesList As ArrayList)
      Dim i As Integer
      For i = 0 To samplesList.Count - 1
         ' Output the sample.
         OutputSample(CType(samplesList(i), CounterSample))
         
         ' Use .NET to calculate the counter value.
         Console.WriteLine((".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample))))
         
         ' Calculate the counter value manually.
         Console.WriteLine(("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample))))
      Next i
   End Sub 'CalculateResults
    
   
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   ' Formula from MSDN -
   '      Description - This counter type shows the ratio of a subset to its set as a percentage.
   '            For example, it compares the number of bytes in use on a disk to the
   '            total number of bytes on the disk. Counters of this type display the 
   '            current percentage only, not an average over time.
   '
   ' Generic type - Instantaneous, Percentage 
   '        Formula - (N0 / D0), where D represents a measured attribute and N represents one
   '            component of that attribute.
   '
   '        Average - SUM (N / D) /x 
   '        Example - Paging File\% Usage Peak
   '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
   Private Shared Function MyComputeCounterValue(rfSample As CounterSample) As [Single]
      Dim numerator As [Single] = CType(rfSample.RawValue, [Single])
      Dim denomenator As [Single] = CType(rfSample.BaseValue, [Single])
      Dim counterValue As [Single] = numerator / denomenator * 100
      Return counterValue
   End Function 'MyComputeCounterValue
   
   
   ' Output information about the counter sample.
   Private Shared Sub OutputSample(s As CounterSample)
      Console.WriteLine("+++++++++++")
      Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
      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("++++++++++++++++++++++")
   End Sub 'OutputSample
End Class 'App 




[C#] 
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("RawFractionSampleCategory") ) 
        {


            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData rf = new CounterCreationData();
            rf.CounterType = PerformanceCounterType.RawFraction;
            rf.CounterName = "RawFractionSample";
            CCDC.Add(rf);
        
            // Add the base counter.
            CounterCreationData rfBase = new CounterCreationData();
            rfBase.CounterType = PerformanceCounterType.RawBase;
            rfBase.CounterName = "RawFractionSampleBase";
            CCDC.Add(rfBase);

            // Create the category.
            PerformanceCounterCategory.Create("RawFractionSampleCategory", 
                "Demonstrates usage of the RawFraction performance counter type.", 
                CCDC);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - RawFractionSampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counters.
        PC = new PerformanceCounter("RawFractionSampleCategory", 
            "RawFractionSample", 
            false);
        
        BPC = new PerformanceCounter("RawFractionSampleCategory", 
            "RawFractionSampleBase", 
            false);
        
        PC.RawValue=0;
        BPC.RawValue=0;
    }

    private static void CollectSamples(ArrayList samplesList)
    {
    
        Random r = new Random( DateTime.Now.Millisecond );

        // Initialize the performance counter.
        PC.NextSample();

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

            // Increment the base every time, because the counter measures the number 
            // of high hits (raw fraction value) against all the hits (base value).
            BPC.Increment();

            // Get the % of samples that are 9 or 10 out of all the samples taken.
            if (value >= 9)
                PC.Increment();

            // Copy out the next value every ten times around the loop.
            if ((j % 10) == 9) 
            {
                Console.WriteLine(";       NextValue() = " + PC.NextValue().ToString());
                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; i++)
        {
            // Output the sample.
            OutputSample( (CounterSample)samplesList[i] );

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

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

        }
    }

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    // Formula from MSDN -
    //      Description - This counter type shows the ratio of a subset to its set as a percentage.
    //            For example, it compares the number of bytes in use on a disk to the
    //            total number of bytes on the disk. Counters of this type display the 
    //            current percentage only, not an average over time.
    //
    // Generic type - Instantaneous, Percentage 
    //        Formula - (N0 / D0), where D represents a measured attribute and N represents one
    //            component of that attribute.
    //
    //        Average - SUM (N / D) /x 
    //        Example - Paging File\% Usage Peak
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample rfSample)
    {
        Single numerator = (Single)rfSample.RawValue;
        Single denomenator = (Single)rfSample.BaseValue;
        Single counterValue = (numerator / denomenator) * 100;
        return(counterValue);
    }

    // Output information about the counter sample.
    private static void OutputSample(CounterSample s)
    {
        Console.WriteLine("+++++++++++");
        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("++++++++++++++++++++++");
    }



}


[C++] 
#using <mscorlib.dll>
#using <System.dll>

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

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
// Formula from MSDN -
//      Description - This counter type shows the ratio of a subset to its set as a percentage.
//            For example, it compares the number of bytes in use on a disk to the
//            total number of bytes on the disk. Counters of this type display the 
//            current percentage only, not an average over time.
//
// Generic type - Instantaneous, Percentage 
//        Formula - (N0 / D0), where D represents a measured attribute and N represents one
//            component of that attribute.
//
//        Average - SUM (N / D) /x 
//        Example - Paging File\% Usage Peak
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
float MyComputeCounterValue(CounterSample rfSample) {
    float numerator = (float)rfSample.RawValue;
    float denomenator = (float)rfSample.BaseValue;
    float counterValue = (numerator / denomenator) * 100;
    return counterValue;
}

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

bool SetupCategory() {
    if (!PerformanceCounterCategory::Exists(S"RawFractionSampleCategory")) {
        CounterCreationDataCollection* CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData* rf = new CounterCreationData();
        rf->CounterType = PerformanceCounterType::RawFraction;
        rf->CounterName = S"RawFractionSample";
        CCDC->Add(rf);

        // Add the base counter.
        CounterCreationData* rfBase = new CounterCreationData();
        rfBase->CounterType = PerformanceCounterType::RawBase;
        rfBase->CounterName = S"RawFractionSampleBase";
        CCDC->Add(rfBase);

        // Create the category.
        PerformanceCounterCategory::Create(S"RawFractionSampleCategory", 
            S"Demonstrates usage of the RawFraction performance counter type.", 
            CCDC);

        return true;
    } else {
        Console::WriteLine(S"Category exists - RawFractionSampleCategory");
        return false;
    }
}

void CreateCounters(PerformanceCounter*& PC, PerformanceCounter*& BPC) {
    // Create the counters.
    PC = new PerformanceCounter(S"RawFractionSampleCategory", 
        S"RawFractionSample", false);
    BPC = new PerformanceCounter(S"RawFractionSampleCategory", 
        S"RawFractionSampleBase", false);

    PC->RawValue=0;
    BPC->RawValue=0;
}

void CollectSamples(ArrayList* samplesList, PerformanceCounter* PC, PerformanceCounter* BPC) {
    Random* r = new Random(DateTime::Now.Millisecond);

    // Initialize the performance counter.
    PC->NextSample();

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

        // Increment the base every time, because the counter measures the number 
        // of high hits (raw fraction value) against all the hits (base value).
        BPC->Increment();

        // Get the % of samples that are 9 or 10 out of all the samples taken.
        if (value >= 9)
            PC->Increment();

        // Copy out the next value every ten times around the loop.
        if ((j % 10) == 9) {
            Console::WriteLine(S";       NextValue() = {0}", __box(PC->NextValue()));
            OutputSample(PC->NextSample());
            samplesList->Add(__box(PC->NextSample()));
        } else
            Console::WriteLine();

        System::Threading::Thread::Sleep(50);
    }
}

void CalculateResults(ArrayList* samplesList) {
    for (int i = 0; i < samplesList->Count; i++) {
        // Output the sample.
        OutputSample(*__try_cast<__box CounterSample*>(samplesList->Item[i]));

        // Use .NET to calculate the counter value.
        Console::WriteLine(S".NET computed counter value = {0}", 
            __box(CounterSampleCalculator::ComputeCounterValue(
            *__try_cast<__box CounterSample*>(samplesList->Item[i]))));

        // Calculate the counter value manually.
        Console::WriteLine(S"My computed counter value = {0}", 
            __box(MyComputeCounterValue(
            *__try_cast<__box CounterSample*>(samplesList->Item[i]))));
    }
}

void main() {    
    ArrayList* samplesList = new ArrayList();
    PerformanceCounter* PC;
    PerformanceCounter* BPC;

    SetupCategory();
    CreateCounters(PC, BPC);
    CollectSamples(samplesList, PC, BPC);
    CalculateResults(samplesList);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Diagnostics

Platforms: Windows NT Server 4.0, Windows NT Workstation 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: System (in System.dll)

See Also

System.Diagnostics Namespace | PerformanceCounter

Show:
© 2014 Microsoft