PerformanceCounter 类

表示 Windows NT 性能计数器组件。

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

语法

声明
Public NotInheritable Class PerformanceCounter
    Inherits Component
    Implements ISupportInitialize
用法
Dim instance As PerformanceCounter
public sealed class PerformanceCounter : Component, ISupportInitialize
public ref class PerformanceCounter sealed : public Component, ISupportInitialize
public final class PerformanceCounter extends Component implements ISupportInitialize
public final class PerformanceCounter extends Component implements ISupportInitialize

备注

提示

应用于该类的 HostProtectionAttribute 属性 (Attribute) 具有以下 Resources 属性 (Property) 值:Synchronization | SharedStateHostProtectionAttribute 并不会影响桌面应用程序(桌面应用程序通常通过双击图标、键入命令或在浏览器中输入 URL 来启动)。有关更多信息,请参见 HostProtectionAttribute 类或 SQL Server 编程和宿主保护属性

PerformanceCounter 组件既可用于读取现有的预定义或自定义计数器,又可用于向自定义计数器发布(写入)性能数据。

Note重要事项:

在 .NET Framework 1.0 版和 1.1 版中,此类要求直接调用方是完全信任的调用方。在 2.0 版中,此类要求 PerformanceCounterPermission 以进行特定操作。强烈建议不要将 PerformanceCounterPermission 授予不完全受信任的代码。读写性能计数器的能力允许代码执行某些操作,如枚举正在执行的进程并获取它们的信息。

警告

向不完全受信任的代码传递 PerformanceCounter 对象可能会引发安全问题。在任何情况下都不要将性能计数器对象(如 PerformanceCounterCategoryPerformanceCounter)传递给不完全受信任的代码。

若要从性能计数器进行读取,请创建 PerformanceCounter 类的一个实例,设置 CategoryNameCounterName 属性,也可选择设置 InstanceNameMachineName 属性,然后调用 NextValue 方法来获取性能计数器读数。

若要发布性能计数器数据,请使用 PerformanceCounterCategory.Create 方法创建一个或多个自定义计数器,创建 PerformanceCounter 类的一个实例,设置 CategoryNameCounterName 属性,并可选择设置 InstanceNameMachineName 属性,然后调用 IncrementByIncrementDecrement 方法,或者设置 RawValue 属性更改自定义计数器的值。

提示

IncrementIncrementByDecrement 方法使用联锁更新计数器值。这有助于在多线程或多进程方案中保持计数器值准确,但同时会导致性能下降。如果不需要联锁操作所提供的准确度,可以直接更新 RawValue 属性以获得多达 5 倍的性能提高。但是,在多线程方案中对计数器值的某些更新可能被忽略,导致数据不准确。

计数器是用以收集性能数据的机制。注册表存储所有计数器的名称,每个计数器均与系统功能的一个特定区域相关。示例包括处理器繁忙时间、内存占用情况或通过某个网络连接接收的字节数。

通过计数器的名称和位置可唯一地标识每个计数器。与文件路径包括驱动器、目录、一个或多个子目录和文件名一样,计数器信息由四个元素组成:计算机、对象、对象实例和计数器名称。

计数器信息必须包括计数器为其测量数据的类别或性能对象。计算机的类别包括物理组件,如处理器、磁盘和内存。还有系统类别,如进程和线程。每个类别均与计算机内的一个功能元素相关,并且为每个类别均分配了一组标准计数器。这些对象列在 Windows 2000 系统监视器内“添加计数器”对话框的“性能对象”下拉列表中,在计数器路径中必须包括它们。性能数据按与其相关的类别进行分组。

某些情况下可存在同一类别的多个副本。例如,几个进程和线程同时运行,并且有些计算机包含多个处理器。类别副本称为类别实例,而且每个实例都有分配给它的一组标准计数器。如果某个类别可有多个实例,则计数器信息中必须包括实例指定。

若要为需要初始值或以前的值以便进行必要计算的计数器获取性能数据,请调用 NextValue 方法两次,并按应用程序的要求使用返回的信息。

Windows 98, Windows Millennium Edition 平台说明: Windows 98 或 Windows Millennium Edition (Me) 不支持性能计数器。

示例

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

继承层次结构

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

线程安全

该类型对于多线程操作是安全的。

平台

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

请参见

参考

PerformanceCounter 成员
System.Diagnostics 命名空间
PerformanceCounterType
CounterCreationData 类
CounterCreationDataCollection 类
CounterSample 结构
CounterSampleCalculator 类