PerformanceCounterType 枚举

PerformanceCounter 实例指定用于计算 NextValue 方法的公式。

**命名空间:**System.Diagnostics
**程序集:**System(在 system.dll 中)

语法

声明
Public Enumeration PerformanceCounterType
用法
Dim instance As PerformanceCounterType
public enum PerformanceCounterType
public enum class PerformanceCounterType
public enum PerformanceCounterType
public enum PerformanceCounterType

成员

  成员名称 说明
AverageBase 在时间或计数的平均值计算中使用的基本计数器(如 AverageTimer32AverageCount64)。存储用于计算表示“每个操作的时间”或“每个操作的计数”的计数器的分母。 
AverageCount64 平均计数器,它显示一次操作中平均处理的项数。这种类型的计数器显示已处理的项与已完成的操作数的比率。计算该比率的方法是将上一个时间间隔内处理的项数与上一个时间间隔内完成的操作数进行比较。 

公式:(N 1 -N 0)/(B 1 -B 0),其中 N 1 和 N 0 是性能计数器读数,B 1 和 B 0 是相应的 AverageBase 值。因此,分子表示取样时间间隔内处理的项数,分母表示取样时间间隔内完成的操作数。

这种类型的计数器包含 PhysicalDisk\ Avg.Disk Bytes/Transfer。

AverageTimer32 平均计数器,它测量完成某个进程或操作平均所花费的时间。这种类型的计数器显示取样时间间隔的总运行时间与该时间内完成的进程或操作数的比率。此计数器类型用系统时钟的滴答来测量时间。 

公式:((N 1 -N 0)/F)/(B 1 -B 0),其中 N 1 和 N 0 是性能计数器读数,B 1 和 B 0 是相应的 AverageBase 值,F 是每秒的滴答数。F 的值被分解为公式的因子,以便可以以秒为单位显示结果。因此,分子表示上一个取样时间间隔内记录的滴答数,F 表示滴答频率,分母表示上一个取样时间间隔内完成的操作数。

这种类型的计数器包含 PhysicalDisk\ Avg.Disk sec/Transfer。

CounterDelta32 差异计数器,它显示在最近的两个取样间隔内已测量属性的更改。 

公式:N 1 -N 0,其中 N 1 和 N 0 是性能计数器读数。

CounterDelta64 差异计数器,它显示在最近的两个取样间隔内已测量属性的更改。它与 CounterDelta32 计数器类型相同,但它使用更大的字段来容纳较大的值。 

公式:N 1 -N 0,其中 N 1 和 N 0 是性能计数器读数。

CounterMultiBase 基本计数器,它指示已取样的项数。它在计算中用作分母,以在获取多个相似项的计时时间时获取已取样项的平均数。与 CounterMultiTimerCounterMultiTimerInverseCounterMultiTimer100NsCounterMultiTimer100NsInverse 一起使用。 
CounterMultiTimer 百分比计数器,它以取样间隔总时间百分比的形式显示一个或多个组件的活动时间。由于分子记录的是同时操作的组件的活动时间,因此最终的百分比可以超过 100%。 

此计数器是多项计时器。多项计时器从组件(如处理器或磁盘)的多个实例中收集数据。此计数器类型与 CounterMultiTimer100Ns 的不同之处在于:它以系统性能计时器的滴答为单位(而不是以 100 毫微秒为单位)来测量时间。

公式:((N 1 - N 0) / (D 1 - D 0)) x 100 / B,其中 N 1 和 N 0 是性能计数器读数,D 1 和 D 0 是以系统性能计时器中的滴答数为单位的相应时间读数,变量 B 表示受监视的组件的基本计数(使用类型为 CounterMultiBase 的基本计数器)。因此,分子表示取样间隔内受监视的组件处于活动状态的部分,分母表示取样间隔的总运行时间。

CounterMultiTimer100Ns 百分比计数器,它以取样间隔总时间百分比的形式显示一个或多个组件的活动时间。它以 100 毫微秒 (ns) 为单位来测量时间。 

此计数器的类型是多项计时器。多项计时器旨在监视组件(如处理器或磁盘)的多个实例。

公式:((N 1 - N 0) / (D 1 - D 0)) x 100 / B,其中 N 1 和 N 0 是性能计数器读数,D 1 和 D 0 是以 100 毫微秒为单位的相应时间读数,变量 B 表示受监视的组件的基本计数(使用类型为 CounterMultiBase 的基本计数器)。因此,分子表示取样间隔内受监视的组件处于活动状态的部分,分母表示取样间隔的总运行时间。

CounterMultiTimer100NsInverse 百分比计数器,它以取样间隔总时间百分比的形式显示一个或多个组件的活动时间。这种类型的计数器以 100 毫微秒 (ns) 为单位来测量时间。它们推导活动时间的方法是测量组件处于非活动状态的时间,然后从受监视的对象数乘以 100% 中减去该结果。 

此计数器类型为一个反向多项计时器。多项计时器旨在监视组件(如处理器或磁盘)的多个实例。反向计数器测量组件处于非活动状态的时间,并根据非活动时间的测量值推导活动时间

公式:(B - ((N 1 - N 0) / (D 1 - D 0))) x 100,其中分母表示取样间隔的总运行时间,分子表示取样间隔内受监视的组件处于非活动状态的时间,B 表示受监视的组件数(使用类型为 CounterMultiBase 的基本计数器)。

CounterMultiTimerInverse 百分比计数器,它以取样间隔总时间百分比的形式显示一个或多个组件的活动时间。它推导活动时间的方法是测量组件处于非活动状态的时间,然后从受监视的对象乘以 100% 中减去该结果。 

此计数器类型为一个反向多项计时器。多项计时器监视组件(如处理器或磁盘)多个实例。反向计数器测量组件处于非活动状态的时间并从该测量值中推导出活动时间。

此计数器与 CounterMultiTimer100NsInverse 的不同之处在于:它是以系统性能计时器的滴答为单位(而不是以 100 毫微秒为单位)来测量时间。

公式:(B- ((N 1 - N 0) / (D 1 - D 0))) x 100,其中分母表示取样间隔的总运行时间,分子表示取样间隔内受监视的组件处于非活动状态的时间,B 表示受监视的组件数(使用类型为 CounterMultiBase 的基本计数器)。

CounterTimer 百分比计数器,它以总取样时间的百分比形式显示组件处于活动状态的平均时间。 

公式:(N 1 - N 0) / (D 1 - D 0),其中 N 1 和 N 0 是性能计数器读数,D 1 和 D 0 是相应的时间读数。因此,分子表示取样间隔内受监视的组件处于活动状态的部分,分母表示取样间隔的总运行时间。

CounterTimerInverse 百分比计数器,它显示在取样时间间隔内观测到的活动时间的平均百分比。计算这些计数器值的方法是监视服务处于非活动状态的时间百分比,然后从 100% 中减去该值。 

这是反向计数器类型。反向计数器计算组件处于非活动状态的时间并从该测量值中推导出活动时间。此计数器类型与 CounterTimer100NsInv 相同,但它是以系统性能计时器的滴答(而不是以 100 毫微秒)为单位来测量时间。

公式:(1- ((N 1 - N 0) / (D 1 - D 0))) x 100,其中分子表示取样间隔内受监视的组件处于非活动状态的时间,分母表示取样间隔的总运行时间。

CountPerTimeInterval32 平均计数器,旨在监视一段时间内资源队列的平均长度。它显示在最近两个取样时间间隔内观测到的队列长度分别除以间隔时间后的差值。此类型的计数器通常用于跟踪排队或等候的项数。 

公式:(N 1 - N 0) / (D 1 - D 0),其中分子表示队列中的项数,分母表示上一个取样时间间隔的运行时间。

CountPerTimeInterval64 平均值计数器,它监视一段时间内资源队列的平均长度。这种类型的计数器显示在最近两个取样间隔内观测到的队列长度分别除以间隔时间后的差值。此计数器类型与 CountPerTimeInterval32 相同,但它使用更大的字段来容纳较大的值。此类型的计数器通常用于跟踪排队或等候的大量项。 

公式:(N 1 - N 0) / (D 1 - D 0),其中分子表示队列中的项数,分母表示取样间隔的运行时间。

ElapsedTime 差异计时器,它显示组件或进程的开始时间与该值的计算时间之间的总时间。 

公式:(D 0 - N 0) / F,其中 D 0 表示当前时间,N 0 表示对象的启动时间,F 表示一秒内经过的时间单位数。F 的值被分解为公式的因子,以便可以以秒为单位显示结果。

这种类型的计数器包括 System\ System Up Time。

NumberOfItems32 即时计数器,它显示最近观测到的值。例如,用于维护项或操作的简单计数。 

公式:无。不显示平均值,但按原样显示收集到的原始数据。

这种类型的计数器包括 Memory\Available Bytes。

NumberOfItems64 即时计数器,它显示最近观测到的值。例如,用于维护大量的项或操作的简单计数。它与 NumberOfItems32 相同,但它使用更大的字段来容纳较大的值。 

公式:无。不显示平均值,但按原样显示收集到的原始数据。

NumberOfItemsHEX32 即时计数器,它以十六进制形式显示最近观测到的值。例如,用于维护项或操作的简单计数。 

公式:无。不显示平均值,但按原样显示收集到的原始数据。

NumberOfItemsHEX64 即时计数器,它显示最近观测到的值。例如,用于维护大量的项或操作的简单计数。它与 NumberOfItemsHEX32 相同,但它使用更大的字段来容纳较大的值。 

公式:无。不显示平均值,但按原样显示收集到的原始数据。

RateOfCountsPerSecond32 差异计数器,它显示在取样间隔的每一秒内完成的操作的平均数目。这种类型的计数器用系统时钟的滴答 (Tick) 来测量时间。 

公式:(N 1 - N 0) / ((D 1 -D 0) / F),其中 N 1 和 N 0 是性能计数器读数,D 1 和 D 0 是相应的时间读数,F 表示每秒的滴答数。因此,分子表示在上一个取样间隔内执行的操作数,分母表示在上一个取样间隔内经过的滴答数,F 是滴答的频率。F 的值被分解为公式的因子,以便可以以秒为单位显示结果。

这种类型的计数器包括 System\ File Read Operations/sec。

RateOfCountsPerSecond64 差异计数器,它显示在取样间隔的每一秒内完成的操作的平均数目。这种类型的计数器用系统时钟的滴答 (Tick) 来测量时间。此计数器类型与 RateOfCountsPerSecond32 类型相同,但它使用更大的字段来容纳较大的值,以跟踪每秒内的大量项数或操作数(如字节传输速率)。 

公式:(N 1 - N 0) / ((D 1 -D 0) / F),其中 N 1 和 N 0 是性能计数器读数,D 1 和 D 0 是相应的时间读数,F 表示每秒的滴答数。因此,分子表示在上一个取样间隔内执行的操作数,分母表示在上一个取样间隔内经过的滴答数,F 是滴答的频率。F 的值被分解为公式的因子,以便可以以秒为单位显示结果。

这种类型的计数器包括 System\ File Read Bytes/sec。

RawBase 基本计数器,它存储表示常规算术分数的计数器的分母。检查以确保此值大于零,然后将它用作 RawFraction 值计算中的分母。 
RawFraction 即时百分比计数器,它以百分比的形式显示子集与其父集的比率。例如,它将磁盘上使用的字节数与该磁盘上的总字节数进行比较。这种类型的计数器只显示当前百分比,而不显示一段时间的平均值。 

公式:(N 0 / D 0) x 100,其中 D 0 表示已测量的属性(使用类型为 RawBase 的基本计数器),N 0 表示该属性的一个组件。

这种类型的计数器包括 Paging File\% Usage Peak。

SampleBase 基本计数器,它存储获取的取样中断数,并在样本分数中用作分母。样本分数是取样中断的值为 1(或 true)的样本数。检查以确保此值大于零,然后再将它用作 SampleCounterSampleFraction 计算中的分母。 
SampleCounter 平均计数器,它显示一秒内完成的平均操作数。当这种类型的计数器对数据进行取样时,每个取样中断返回一或零。该计数器数据是取样的个数。它以系统性能计时器的滴答为单位来测量时间。 

公式:(N 1 – N 0) / ((D 1 – D 0) / F),其中分子 (N) 表示已完成的操作数,分母 (D) 表示系统性能计时器的运行时间(以滴答为单位),F 表示每秒经过的滴答数。F 被分解为公式的因子,以便可以以秒为单位显示结果。

SampleFraction 百分比计数器,它显示最近两个取样时间间隔内的命中与所有操作的平均比率。 

公式:((N 1 - N 0) / (D 1 - D 0)) x 100,其中分子表示上一个取样时间间隔内成功完成的操作数,分母表示取样时间间隔内完成的(已测量类型的)所有操作数的更改(使用类型为 SampleBase 的计数器)。

这种类型的计数器包括 Cache\Pin Read Hits %。

Timer100Ns 百分比计数器,它以取样时间间隔的总运行时间的百分比形式显示组件的活动时间。它以 100 毫微秒 (ns) 为单位来测量时间。这种类型的计数器旨在一次测量一个组件的活动。 

公式:(N 1 - N 0) / (D 1 - D 0) x 100,其中分子表示取样时间间隔内受监视的组件处于活动状态的时间,分母表示取样时间间隔的总运行时间。

这种类型的计数器包括 Processor\ % User Time。

Timer100NsInverse 百分比计数器,它显示取样时间间隔内观测到的活动时间的平均百分比。 

这是反向计数器。这种类型的计数器计算活动时间的方法是测量服务处于非活动状态的时间,然后从 100% 中减去活动时间的百分比。

公式:(1- ((N 1 - N 0) / (D 1 - D 0))) x 100,其中分子表示取样间隔内受监视的组件处于非活动状态的时间,分母表示取样间隔的总运行时间。

这种类型的计数器包括 Processor\ % Processor Time。

备注

有些计数器类型表示原始数据,有些则表示基于一个或多个计数器样本的计算所得值。下列类别对可用的计数器类型进行了分类。

  • 平均:测量一段时间的值并显示最后两次测量值的平均值。与每个平均计数器关联的是跟踪所涉及的取样数的基本计数器。

  • 差异:将最后一个测量值从前一个测量值中减去,如果差值为正,则显示差值;如果为负,则它们显示零。

  • 即时:显示最近的测量值。

  • 百分比:以百分比的形式显示计算所得值。

  • 速率:对一段时间内增加的事件计数进行取样,并用计数值变化除以时间变化以显示活动速率。

对性能计数器数据进行取样时,使用表示平均值的计数器类型可以使原始数据值有益您的应用。例如,原始数据计数器 NumberOfItems64 可以公开从一个样本到另一个样本相当随机的数据。用于计算计数器返回值的平均数的公式为 (X 0 +X 1 +…+X n)/n,其中每个 X i 都是一个原始计数器样本。

速率计数器类似于平均计数器,但对于速率随资源的使用而增加的情况更为有用。快速计算平均数的公式为 ((X n -X 0)/(T n -T 0)) / 频率,其中每个 X i 都是一个计数器样本,每个 T i 都是相应样本的取样时间。结果为每秒的平均使用率。

提示

除非另有指示,否则时间基数为秒。

规范应用程序(创建和编写自定义性能计数器)时,可能要使用依赖于计算中所用的伴随的基本计数器的性能计数器类型。基本计数器必须紧跟在它在应用程序使用的 CounterCreationDataCollection 集合中的关联计数器之后。下表列出了基计数器类型及其对应的性能计数器类型。

基本计数器类型

性能计数器类型

AverageBase

AverageTimer32

AverageCount64

CounterMultiBase

CounterMultiTimer

CounterMultiTimerInverse

CounterMultiTimer100Ns

CounterMultiTimer100NsInverse

RawBase

RawFraction

SampleBase

SampleCounter

SampleFraction

示例

以下示例阐释了 PerformanceCounterType 枚举中的几种计数器类型。

AverageCount64

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
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("++++++++++++++++++++++");
    }
}
#using <System.dll>

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

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

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

bool SetupCategory()
{
   if (  !PerformanceCounterCategory::Exists( "AverageCounter64SampleCategory" ) )
   {
      CounterCreationDataCollection^ CCDC = gcnew CounterCreationDataCollection;
      
      // Add the counter.
      CounterCreationData^ averageCount64 = gcnew CounterCreationData;
      averageCount64->CounterType = PerformanceCounterType::AverageCount64;
      averageCount64->CounterName = "AverageCounter64Sample";
      CCDC->Add( averageCount64 );
      
      // Add the base counter.
      CounterCreationData^ averageCount64Base = gcnew CounterCreationData;
      averageCount64Base->CounterType = PerformanceCounterType::AverageBase;
      averageCount64Base->CounterName = "AverageCounter64SampleBase";
      CCDC->Add( averageCount64Base );
      
      // Create the category.
      PerformanceCounterCategory::Create( "AverageCounter64SampleCategory", "Demonstrates usage of the AverageCounter64 performance counter type.", CCDC );
      return (true);
   }
   else
   {
      Console::WriteLine( "Category exists - AverageCounter64SampleCategory" );
      return (false);
   }
}

void CreateCounters( PerformanceCounter^% PC, PerformanceCounter^% BPC )
{
   
   // Create the counters.
   PC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64Sample",false );

   BPC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64SampleBase",false );
   PC->RawValue = 0;
   BPC->RawValue = 0;
}

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

   // Loop for the samples.
   for ( int j = 0; j < 100; j++ )
   {
      int value = r->Next( 1, 10 );
      Console::Write( "{0} = {1}", j, value );
      PC->IncrementBy( value );
      BPC->Increment();
      if ( (j % 10) == 9 )
      {
         OutputSample( PC->NextSample() );
         samplesList->Add( 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(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );
      
      // Use .NET to calculate the counter value.
      Console::WriteLine( ".NET computed counter value = {0}", CounterSampleCalculator::ComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );
      
      // Calculate the counter value manually.
      Console::WriteLine( "My computed counter value = {0}", MyComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );
   }
}

int main()
{
   ArrayList^ samplesList = gcnew ArrayList;
   PerformanceCounter^ PC;
   PerformanceCounter^ BPC;
   SetupCategory();
   CreateCounters( PC, BPC );
   CollectSamples( samplesList, PC, BPC );
   CalculateResults( samplesList );
}
import System.*;  
import System.Collections.*;  
import System.Collections.Specialized.*;  
import System.Diagnostics.*;  

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

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

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

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

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

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

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

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

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

AverageTimer32

Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic

Public Class App

    Private Const categoryName As String = "AverageTimer32SampleCategory"
    Private Const counterName As String = "AverageTimer32Sample"
    Private Const baseCounterName As String = "AverageTimer32SampleBase"

    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(categoryName) Then

            Dim CCDC As New CounterCreationDataCollection()

            ' Add the counter.
            Dim averageTimer32 As New CounterCreationData()
            averageTimer32.CounterType = PerformanceCounterType.AverageTimer32
            averageTimer32.CounterName = counterName
            CCDC.Add(averageTimer32)

            ' Add the base counter.
            Dim averageTimer32Base As New CounterCreationData()
            averageTimer32Base.CounterType = PerformanceCounterType.AverageBase
            averageTimer32Base.CounterName = baseCounterName
            CCDC.Add(averageTimer32Base)

            ' Create the category.
            PerformanceCounterCategory.Create( _
               categoryName, _
               "Demonstrates usage of the AverageTimer32 performance counter type", _
                 PerformanceCounterCategoryType.SingleInstance, CCDC)

            Console.WriteLine("Category created - " + categoryName)

            Return True
        Else
            Console.WriteLine(("Category exists - " + _
               categoryName))
            Return False
        End If
    End Function


    Private Shared Sub CreateCounters()
        ' Create the counters.
        PC = New PerformanceCounter(categoryName, _
              counterName, False)

        BPC = New PerformanceCounter(categoryName, _
              baseCounterName, False)

        PC.RawValue = 0
        BPC.RawValue = 0
    End Sub


    Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)

        Dim r As New Random(DateTime.Now.Millisecond)

        ' Loop for the samples.
        Dim i As Integer
        For i = 0 To 9

            PC.RawValue = Stopwatch.GetTimeStamp()

            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(ByVal 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( _
    ByVal s0 As CounterSample, _
    ByVal 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(ByVal s As CounterSample)
        Console.WriteLine("+++++++++++")
        Console.WriteLine("Sample values - " + ControlChars.Cr _
              + ControlChars.Lf)
        Console.WriteLine(("   CounterType      = " + _
              s.CounterType.ToString()))
        Console.WriteLine(("   RawValue         = " + _
              s.RawValue.ToString()))
        Console.WriteLine(("   BaseValue        = " _
              + s.BaseValue.ToString()))
        Console.WriteLine(("   CounterFrequency = " + _
              s.CounterFrequency.ToString()))
        Console.WriteLine(("   CounterTimeStamp = " + _
              s.CounterTimeStamp.ToString()))
        Console.WriteLine(("   SystemFrequency  = " + _
              s.SystemFrequency.ToString()))
        Console.WriteLine(("   TimeStamp        = " + _
              s.TimeStamp.ToString()))
        Console.WriteLine(("   TimeStamp100nSec = " + _
              s.TimeStamp100nSec.ToString()))
        Console.WriteLine("++++++++++++++++++++++")
    End Sub


End Class
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;

    private const String categoryName = "AverageTimer32SampleCategory";
    private const String counterName = "AverageTimer32Sample";
    private const String baseCounterName = "AverageTimer32SampleBase";

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

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




    private static bool SetupCategory()
    {

        if (!PerformanceCounterCategory.Exists(categoryName))
        {

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageTimer32 = new CounterCreationData();
            averageTimer32.CounterType = PerformanceCounterType.AverageTimer32;
            averageTimer32.CounterName = counterName;
            CCDC.Add(averageTimer32);

            // Add the base counter.
            CounterCreationData averageTimer32Base = new CounterCreationData();
            averageTimer32Base.CounterType = PerformanceCounterType.AverageBase;
            averageTimer32Base.CounterName = baseCounterName;
            CCDC.Add(averageTimer32Base);

            // Create the category.
            PerformanceCounterCategory.Create(categoryName, 
                "Demonstrates usage of the AverageTimer32 performance counter type", 
                PerformanceCounterCategoryType.SingleInstance, CCDC);

            Console.WriteLine("Category created - " + categoryName);

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

    private static void CreateCounters()
    {
        // Create the counters.
        PC = new PerformanceCounter(categoryName,
                 counterName,
                 false);

        BPC = new PerformanceCounter(categoryName,
            baseCounterName,
            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 i = 0; i < 10; i++)
        {

            PC.RawValue = Stopwatch.GetTimestamp();

            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("   CounterType      = " + s.CounterType);
        Console.WriteLine("   RawValue         = " + s.RawValue);
        Console.WriteLine("   BaseValue        = " + s.BaseValue);
        Console.WriteLine("   CounterFrequency = " + s.CounterFrequency);
        Console.WriteLine("   CounterTimeStamp = " + s.CounterTimeStamp);
        Console.WriteLine("   SystemFrequency  = " + s.SystemFrequency);
        Console.WriteLine("   TimeStamp        = " + s.TimeStamp);
        Console.WriteLine("   TimeStamp100nSec = " + s.TimeStamp100nSec);
        Console.WriteLine("++++++++++++++++++++++");
    }
}

ElapsedTime

Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic

Public Class App
   
   Public Shared Sub Main()
      CollectSamples()
   End Sub
   
   Private Shared Sub CollectSamples()

      Dim categoryName as String = "ElapsedTimeSampleCategory"
      Dim counterName as String = "ElapsedTimeSample"

      If Not PerformanceCounterCategory.Exists(categoryName) Then
         
         Dim CCDC As New CounterCreationDataCollection()
         
         ' Add the counter.
         Dim ETimeData As New CounterCreationData()
         ETimeData.CounterType = PerformanceCounterType.ElapsedTime
         ETimeData.CounterName = counterName
         CCDC.Add(ETimeData)
         
         ' Create the category.
         PerformanceCounterCategory.Create(categoryName, _
            "Demonstrates ElapsedTime performance counter usage.", CCDC)
       
      Else
         Console.WriteLine("Category exists - {0}", categoryName)
      End If

      ' Create the counter.
      Dim PC As PerformanceCounter
      PC = New PerformanceCounter(categoryName, counterName, False)
     
      ' Initialize the counter.
      PC.RawValue = Stopwatch.GetTimestamp()

      Dim Start As DateTime = DateTime.Now
      
      ' Loop for the samples.
      Dim j As Integer
      For j = 0 To 99
         ' 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())
         End If
         
         ' Reset the counter every 20th iteration.
         If j Mod 20 = 0 Then
            PC.RawValue = Stopwatch.GetTimestamp()
            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
End Class
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime.InteropServices;

public class App 
{

    public static void Main()
    {   
        CollectSamples();
    }

   
    public static void CollectSamples()
    {
        const String categoryName = "ElapsedTimeSampleCategory";
        const String counterName = "ElapsedTimeSample";

        if ( !PerformanceCounterCategory.Exists(categoryName) ) 
        {

            CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

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

        }
        else
        {
            Console.WriteLine("Category exists - {0}", categoryName);
        }        

        // Create the performance counter.
        PerformanceCounter PC = new PerformanceCounter(categoryName, 
                                                       counterName, 
                                                       false);
        // Initialize the counter.
        PC.RawValue = Stopwatch.GetTimestamp();

        DateTime Start = DateTime.Now;

        // Loop for the samples.
        for (int j = 0; j < 100; 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());
            }

            // Reset the counter on every 20th iteration.
            if (j % 20 == 0)
            {
                PC.RawValue = Stopwatch.GetTimestamp();
                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("++++++++++++++++++++++");
    }
}
#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( "\r\n+++++++++++" );
   Console::WriteLine( "Sample values - \r\n" );
   Console::WriteLine( "   BaseValue        = {0}", s.BaseValue );
   Console::WriteLine( "   CounterFrequency = {0}", s.CounterFrequency );
   Console::WriteLine( "   CounterTimeStamp = {0}", s.CounterTimeStamp );
   Console::WriteLine( "   CounterType      = {0}", s.CounterType );
   Console::WriteLine( "   RawValue         = {0}", s.RawValue );
   Console::WriteLine( "   SystemFrequency  = {0}", s.SystemFrequency );
   Console::WriteLine( "   TimeStamp        = {0}", s.TimeStamp );
   Console::WriteLine( "   TimeStamp100nSec = {0}", s.TimeStamp100nSec );
   Console::WriteLine( "++++++++++++++++++++++" );
}

void CollectSamples()
{
   String^ categoryName = "ElapsedTimeSampleCategory";
   String^ counterName = "ElapsedTimeSample";
   
   // Create the performance counter category.
   if (  !PerformanceCounterCategory::Exists( categoryName ) )
   {
      CounterCreationDataCollection^ CCDC = gcnew CounterCreationDataCollection;
      
      // Add the counter.
      CounterCreationData^ ETimeData = gcnew CounterCreationData;
      ETimeData->CounterType = PerformanceCounterType::ElapsedTime;
      ETimeData->CounterName = counterName;
      CCDC->Add( ETimeData );
      
      // Create the category.
      PerformanceCounterCategory::Create( categoryName,
         "Demonstrates ElapsedTime performance counter usage.",
         CCDC );
   }
   else
   {
      Console::WriteLine( "Category exists - {0}", categoryName );
   }

   
   // Create the performance counter.
   PerformanceCounter^ PC = gcnew PerformanceCounter( categoryName,
                                                      counterName,
                                                      false );
   // Initialize the counter.
   PC->RawValue = Stopwatch::GetTimestamp();

   DateTime Start = DateTime::Now;
   
   // Loop for the samples.
   for ( int j = 0; j < 100; j++ )
   {
      // Output the values.
      if ( (j % 10) == 9 )
      {
         Console::WriteLine( "NextValue() = {0}", PC->NextValue() );
         Console::WriteLine( "Actual elapsed time = {0}", DateTime::Now.Subtract( Start ) );
         OutputSample( PC->NextSample() );
      }
      
      // Reset the counter on every 20th iteration.
      if ( j % 20 == 0 )
      {
         PC->RawValue = Stopwatch::GetTimestamp();
         Start = DateTime::Now;
      }
      System::Threading::Thread::Sleep( 50 );
   }

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

int main()
{
   CollectSamples();
}
import System.*;
import System.Collections.*;
import System.Collections.Specialized.*;
import System.Diagnostics.*;
import System.Runtime.InteropServices.*;

public class App
{
    public static void main(String[] args)
    {
        CollectSamples();
    } //main

    public static void CollectSamples()
    {
        final String categoryName = "ElapsedTimeSampleCategory";
        final String counterName = "ElapsedTimeSample";

        if (!(PerformanceCounterCategory.Exists(categoryName))) {
            CounterCreationDataCollection ccdc = 
                new CounterCreationDataCollection();
            // Add the counter.
            CounterCreationData eTimeData = new CounterCreationData();
            eTimeData.set_CounterType(PerformanceCounterType.ElapsedTime);
            eTimeData.set_CounterName(counterName);
            ccdc.Add(eTimeData);
            // Create the category.
            PerformanceCounterCategory.Create(categoryName, 
                "Demonstrates ElapsedTime performance counter usage.", ccdc);
        }
        else {
            Console.WriteLine("Category exists - {0}", categoryName);
        }
        // Create the performance counter.
        PerformanceCounter pc = new PerformanceCounter(categoryName,
            counterName, false);
        // Initialize the counter.
        pc.set_RawValue(Stopwatch.GetTimestamp());
        DateTime start = DateTime.get_Now();
        // Loop for the samples.
        for (int j = 0; j < 100; j++) {
            // Output the values.
            if (j % 10 == 9) {
                Console.WriteLine("NextValue() = " + ((Single)pc.NextValue()).
                    ToString());
                Console.WriteLine("Actual elapsed time = "
                    + DateTime.get_Now().Subtract(start).ToString());
                OutputSample(pc.NextSample());
            }
            // Reset the counter on every 20th iteration.
            if (j % 20 == 0) {
                pc.set_RawValue(Stopwatch.GetTimestamp());
                start = DateTime.get_Now();
            }
            System.Threading.Thread.Sleep(50);
        }
        Console.WriteLine("Elapsed time = " + DateTime.get_Now().
            Subtract(start).ToString());
    } //CollectSamples

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

NumberOfItems32

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 

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


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

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

      // Add the counter.
      CounterCreationData^ NOI64 = gcnew 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;
   }
}

void CreateCounters( PerformanceCounter^% PC )
{
   // Create the counter.
   PC = gcnew PerformanceCounter( "NumberOfItems32SampleCategory","NumberOfItems32Sample",false );
   PC->RawValue = 0;
}

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

   // Loop for the samples.
   for ( int j = 0; j < 100; j++ )
   {
      int value = r->Next( 1, 10 );
      Console::Write( "{0} = {1}", j, value );
      PC->IncrementBy( value );
      if ( (j % 10) == 9 )
      {
         OutputSample( PC->NextSample() );
         samplesList->Add( PC->NextSample() );
      }
      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(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );

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

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

void main()
{
   ArrayList^ samplesList = gcnew ArrayList;
   PerformanceCounter^ PC;
   SetupCategory();
   CreateCounters( PC );
   CollectSamples( samplesList, PC );
   CalculateResults( samplesList );
}

NumberOfItems64

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

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

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

      // Add the counter.
      CounterCreationData^ NOI64 = gcnew 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;
   }
}

void CreateCounters( PerformanceCounter^% PC )
{
   // Create the counters.
   PC = gcnew PerformanceCounter( "NumberOfItems64SampleCategory","NumberOfItems64Sample",false );
   PC->RawValue = 0;
}

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

   // Loop for the samples.
   for ( int j = 0; j < 100; j++ )
   {
      int value = r->Next( 1, 10 );
      Console::Write( "{0} = {1}", j, value );
      PC->IncrementBy( value );
      if ( (j % 10) == 9 )
      {
         OutputSample( PC->NextSample() );
         samplesList->Add( PC->NextSample() );
      }
      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(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );

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

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

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

RateOfCountsPerSecond32

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

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

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

      // Add the counter.
      CounterCreationData^ rateOfCounts32 = gcnew 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;
   }
}

void CreateCounters( PerformanceCounter^% PC )
{
   // Create the counter.
   PC = gcnew PerformanceCounter( "RateOfCountsPerSecond32SampleCategory","RateOfCountsPerSecond32Sample",false );
   PC->RawValue = 0;
}

void CollectSamples( ArrayList^ samplesList, PerformanceCounter^ PC )
{
   Random^ r = gcnew 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( "{0} = {1}", j, value );
      if ( (j % 10) == 9 )
      {
         Console::WriteLine( ";       NextValue() = {0}", PC->NextValue() );
         OutputSample( PC->NextSample() );
         samplesList->Add( 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(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );

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

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

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

RateOfCountsPerSecond64

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

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

      // Add the counter.
      CounterCreationData^ rateOfCounts64 = gcnew 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;
   }
}

void CreateCounters( PerformanceCounter^% PC )
{
   // Create the counter.
   PC = gcnew PerformanceCounter( "RateOfCountsPerSecond64SampleCategory","RateOfCountsPerSecond64Sample",false );
   PC->RawValue = 0;
}

void CollectSamples( ArrayList^ samplesList, PerformanceCounter^ PC )
{
   Random^ r = gcnew 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( "{0} = {1}", j, value );
      if ( (j % 10) == 9 )
      {
         Console::WriteLine( ";       NextValue() = {0}", PC->NextValue() );
         OutputSample( PC->NextSample() );
         samplesList->Add( 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(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );

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

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

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

RawFraction

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 


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



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

bool SetupCategory()
{
   if (  !PerformanceCounterCategory::Exists( "RawFractionSampleCategory" ) )
   {
      CounterCreationDataCollection^ CCDC = gcnew CounterCreationDataCollection;
      
      // Add the counter.
      CounterCreationData^ rf = gcnew CounterCreationData;
      rf->CounterType = PerformanceCounterType::RawFraction;
      rf->CounterName = "RawFractionSample";
      CCDC->Add( rf );
      
      // Add the base counter.
      CounterCreationData^ rfBase = gcnew 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;
   }
}

void CreateCounters( PerformanceCounter^% PC, PerformanceCounter^% BPC )
{
   
   // Create the counters.
   PC = gcnew PerformanceCounter( "RawFractionSampleCategory","RawFractionSample",false );
   BPC = gcnew PerformanceCounter( "RawFractionSampleCategory","RawFractionSampleBase",false );
   PC->RawValue = 0;
   BPC->RawValue = 0;
}

void CollectSamples( ArrayList^ samplesList, PerformanceCounter^ PC, PerformanceCounter^ BPC )
{
   Random^ r = gcnew 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( "{0} = {1}", 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() = {0}", PC->NextValue() );
         OutputSample( PC->NextSample() );
         samplesList->Add( 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(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      
      // Use .NET to calculate the counter value.
      Console::WriteLine( ".NET computed counter value = {0}", CounterSampleCalculator::ComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]) ) );
      
      // Calculate the counter value manually.
      Console::WriteLine( "My computed counter value = {0}", MyComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]) ) );

   }
}

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

平台

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

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

System.Diagnostics 命名空间
PerformanceCounter 类