次の方法で共有


PerformanceCounter クラス

定義

Windows NT パフォーマンス カウンター コンポーネントを表します。

public ref class PerformanceCounter sealed : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public sealed class PerformanceCounter : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type PerformanceCounter = class
    inherit Component
    interface ISupportInitialize
Public NotInheritable Class PerformanceCounter
Inherits Component
Implements ISupportInitialize
継承
PerformanceCounter
実装

次のコード例は、 PerformanceCounter クラスを使用して、 AverageCount64 カウンター型を作成して使用する方法を示しています。 この例では、カテゴリを作成し、カウンターを設定し、カウンターからデータを収集し、 CounterSampleCalculator クラスを呼び出してパフォーマンス カウンター データを解釈します。 中間結果と最終結果がコンソール ウィンドウに表示されます。 その他のパフォーマンス カウンターの種類のその他の例については、 PerformanceCounterType 列挙型を参照してください。

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

public class App
{
    private static PerformanceCounter avgCounter64Sample;
    private static PerformanceCounter avgCounter64SampleBase;

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

        // If the category does not exist, create the category and exit.
        // Performance counters should not be created and immediately used.
        // There is a latency time to enable the counters, they should be created
        // prior to executing the application that uses the counters.
        // Execute this sample a second time to use the category.
        if (SetupCategory())
            return;
        CreateCounters();
        CollectSamples(samplesList);
        CalculateResults(samplesList);
    }

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

            CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageCount64 = new CounterCreationData();
            averageCount64.CounterType = PerformanceCounterType.AverageCount64;
            averageCount64.CounterName = "AverageCounter64Sample";
            counterDataCollection.Add(averageCount64);

            // Add the base counter.
            CounterCreationData averageCount64Base = new CounterCreationData();
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
            averageCount64Base.CounterName = "AverageCounter64SampleBase";
            counterDataCollection.Add(averageCount64Base);

            // Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                PerformanceCounterCategoryType.SingleInstance, counterDataCollection);

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

    private static void CreateCounters()
    {
        // Create the counters.

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


        avgCounter64SampleBase = new PerformanceCounter("AverageCounter64SampleCategory",
            "AverageCounter64SampleBase",
            false);

        avgCounter64Sample.RawValue=0;
        avgCounter64SampleBase.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);

            avgCounter64Sample.IncrementBy(value);

            avgCounter64SampleBase.Increment();

            if ((j % 10) == 9)
            {
                OutputSample(avgCounter64Sample.NextSample());
                samplesList.Add( avgCounter64Sample.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("++++++++++++++++++++++");
    }
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class App

    Private Shared avgCounter64Sample As PerformanceCounter
    Private Shared avgCounter64SampleBase As PerformanceCounter


    Public Shared Sub Main()

        Dim samplesList As New ArrayList()
        'If the category does not exist, create the category and exit.
        'Performance counters should not be created and immediately used.
        'There is a latency time to enable the counters, they should be created
        'prior to executing the application that uses the counters.
        'Execute this sample a second time to use the counters.
        If Not (SetupCategory()) Then
            CreateCounters()
            CollectSamples(samplesList)
            CalculateResults(samplesList)
        End If

    End Sub

    Private Shared Function SetupCategory() As Boolean
        If Not PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") Then

            Dim counterDataCollection As New CounterCreationDataCollection()

            ' Add the counter.
            Dim averageCount64 As New CounterCreationData()
            averageCount64.CounterType = PerformanceCounterType.AverageCount64
            averageCount64.CounterName = "AverageCounter64Sample"
            counterDataCollection.Add(averageCount64)

            ' Add the base counter.
            Dim averageCount64Base As New CounterCreationData()
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase
            averageCount64Base.CounterName = "AverageCounter64SampleBase"
            counterDataCollection.Add(averageCount64Base)

            ' Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory", _
               "Demonstrates usage of the AverageCounter64 performance counter type.", _
                      PerformanceCounterCategoryType.SingleInstance, counterDataCollection)

            Return True
        Else
            Console.WriteLine("Category exists - AverageCounter64SampleCategory")
            Return False
        End If
    End Function 'SetupCategory

    Private Shared Sub CreateCounters()
        ' Create the counters.

        avgCounter64Sample = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64Sample", False)

        avgCounter64SampleBase = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64SampleBase", False)

        avgCounter64Sample.RawValue = 0
        avgCounter64SampleBase.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 j As Integer
        For j = 0 To 99

            Dim value As Integer = r.Next(1, 10)
            Console.Write(j.ToString() + " = " + value.ToString())

            avgCounter64Sample.IncrementBy(value)

            avgCounter64SampleBase.Increment()

            If j Mod 10 = 9 Then
                OutputSample(avgCounter64Sample.NextSample())
                samplesList.Add(avgCounter64Sample.NextSample())
            Else
                Console.WriteLine()
            End If
            System.Threading.Thread.Sleep(50)
        Next j
    End Sub

    Private Shared Sub CalculateResults(ByVal 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)).ToString())

            ' Calculate the counter value manually.
            Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
        Next i
    End Sub

    '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    '	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(ByVal s0 As CounterSample, ByVal 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(ByVal s As CounterSample)
        Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
        Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
        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

注釈

PerformanceCounter コンポーネントは、既存の定義済みカウンターまたはカスタム カウンターの読み取りと、カスタム カウンターへのパフォーマンス データの発行 (書き込み) の両方に使用できます。

Windows パフォーマンス モニターの [カウンターの 追加] ダイアログ ボックスには、多数の定義済みカウンターが一覧表示されています。 .NET Framework のパフォーマンス カウンターの詳細については、「 パフォーマンス カウンター」を参照してください。

この型は、IDisposable インターフェイスを実装します。 型の使用が完了したら、直接または間接的に破棄する必要があります。 型を直接破棄するには、Disposetry/ ブロックでその catch メソッドを呼び出します。 間接的に破棄するには、using (C#) や Using (Visual Basic) などの言語コンストラクトを使用します。 詳細については、 IDisposable インターフェイスのトピックの「IDisposable を実装するオブジェクトの使用」セクションを参照してください。

Important

.NET Framework のバージョン 1.0 および 1.1 では、このクラスでは、直ちに呼び出し元を完全に信頼する必要があります。 .NET Framework バージョン 2.0 以降では、このクラスには特定のアクションの PerformanceCounterPermission が必要です。 PerformanceCounterPermission半信頼コードには付与しないことを強くお勧めします。 パフォーマンス カウンターの読み取りと書き込みを行う機能により、コードは、実行中のプロセスの列挙やそれらに関する情報の取得などのアクションを実行できます。

さらに、信頼できないコードに PerformanceCounter オブジェクトを渡すと、セキュリティの問題が発生する可能性があります。 PerformanceCounterCategoryPerformanceCounterなどのパフォーマンス カウンター オブジェクトを信頼度の低いコードに渡すことはありません。

パフォーマンス カウンターから読み取る場合は、 PerformanceCounter クラスのインスタンスを作成し、 CategoryNameCounterName、必要に応じて、 InstanceName または MachineName プロパティを設定してから、 NextValue メソッドを呼び出してパフォーマンス カウンターの読み取りを実行します。

パフォーマンス カウンター データを発行するには、 PerformanceCounterCategory.Create メソッドを使用して 1 つ以上のカスタム カウンターを作成し、 PerformanceCounter クラスのインスタンスを作成し、 CategoryNameCounterName 、必要に応じて、 InstanceName プロパティまたは MachineName プロパティを設定してから、 IncrementByIncrement、または Decrement メソッドを呼び出すか、 RawValue プロパティを設定してカスタム カウンターの値を変更します。

IncrementIncrementBy、およびDecrementメソッドは、インターロックを使用してカウンター値を更新します。 これにより、マルチスレッドまたはマルチプロセスのシナリオでカウンター値を正確に保つことができますが、パフォーマンスが低下します。 インターロックされた操作で提供される精度が不要な場合は、最大 5 倍のパフォーマンス向上のために、 RawValue プロパティを直接更新できます。 ただし、マルチスレッド シナリオでは、カウンター値の一部の更新が無視され、データが不正確になる可能性があります。

カウンターは、パフォーマンス データを収集するメカニズムです。 レジストリにはすべてのカウンターの名前が格納され、各カウンターはシステム機能の特定の領域に関連します。 たとえば、プロセッサのビジー時間、メモリ使用量、ネットワーク接続経由で受信したバイト数などがあります。

各カウンターは、その名前とその場所によって一意に識別されます。 ファイル パスにドライブ、ディレクトリ、1 つ以上のサブディレクトリ、ファイル名が含まれているのと同じように、カウンター情報は、コンピューター、カテゴリ、カテゴリ インスタンス、カウンター名の 4 つの要素で構成されます。

カウンター情報には、カウンターがデータを測定するカテゴリ (パフォーマンス オブジェクト) を含める必要があります。 コンピューターのカテゴリには、プロセッサ、ディスク、メモリなどの物理コンポーネントが含まれます。 プロセスやスレッドなどのシステム カテゴリもあります。 各カテゴリは、コンピューター内の機能要素に関連し、一連の標準カウンターが割り当てられます。 これらのオブジェクトは、Windows 2000 システム モニター内の [カウンターの追加] ダイアログ ボックスの [パフォーマンス オブジェクト] ドロップダウン リストに表示され、カウンター パスに含める必要があります。 パフォーマンス データは、関連するカテゴリ別にグループ化されます。

場合によっては、同じカテゴリの複数のコピーが存在する可能性があります。 たとえば、複数のプロセスとスレッドが同時に実行され、一部のコンピューターには複数のプロセッサが含まれています。 カテゴリ のコピーはカテゴリ インスタンスと呼ばれ、各インスタンスには一連の標準カウンターが割り当てられます。 カテゴリに複数のインスタンスを含めることができる場合は、カウンター情報にインスタンスの指定を含む必要があります。

必要な計算を実行するために初期値または前の値を必要とするカウンターのパフォーマンス データを取得するには、 NextValue メソッドを 2 回呼び出し、アプリケーションで必要な情報を使用します。

.NET と共にインストールされたパフォーマンス カウンター カテゴリでは、個別の共有メモリが使用され、各パフォーマンス カウンター カテゴリには独自のメモリがあります。 個別の共有メモリのサイズを指定するには、レジストリ キーに FileMappingSize という名前の DWORD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<名前>\Performance を作成します。 FileMappingSize 値は、カテゴリの共有メモリ サイズに設定されます。 既定のサイズは 10 進数131072です。 FileMappingSize 値が存在しない場合は、Machine.config ファイルで指定されたperformanceCounters要素のfileMappingSize属性値が使用され、構成ファイルの処理に追加のオーバーヘッドが発生します。 レジストリでファイル マッピング サイズを設定することで、アプリケーションの起動のパフォーマンスを向上させることができます。 ファイル マッピング サイズの詳細については、「 <performanceCounters>を参照してください。

コンストラクター

名前 説明
PerformanceCounter()

インスタンスをシステムまたはカスタム パフォーマンス カウンターに関連付けずに、 PerformanceCounter クラスの新しい読み取り専用インスタンスを初期化します。

PerformanceCounter(String, String, Boolean)

PerformanceCounter クラスの新しい読み取り専用または読み取り/書き込みインスタンスを初期化し、ローカル コンピューター上の指定されたシステムまたはカスタム パフォーマンス カウンターに関連付けます。 このコンストラクターでは、カテゴリに 1 つのインスタンスが含まれている必要があります。

PerformanceCounter(String, String, String, Boolean)

PerformanceCounter クラスの新しい読み取り専用または読み取り/書き込みインスタンスを初期化し、ローカル コンピューター上の指定されたシステムまたはカスタム パフォーマンス カウンターとカテゴリ インスタンスに関連付けます。

PerformanceCounter(String, String, String, String)

PerformanceCounter クラスの新しい読み取り専用インスタンスを初期化し、指定したコンピューター上の指定したシステムまたはカスタム パフォーマンス カウンターおよびカテゴリ インスタンスに関連付けます。

PerformanceCounter(String, String, String)

PerformanceCounter クラスの新しい読み取り専用インスタンスを初期化し、ローカル コンピューター上の指定されたシステム またはカスタム パフォーマンス カウンターおよびカテゴリ インスタンスに関連付けます。

PerformanceCounter(String, String)

PerformanceCounter クラスの新しい読み取り専用インスタンスを初期化し、ローカル コンピューター上の指定されたシステム またはカスタム パフォーマンス カウンターに関連付けます。 このコンストラクターでは、カテゴリに 1 つのインスタンスが必要です。

フィールド

名前 説明
DefaultFileMappingSize
古い.
古い.
古い.

パフォーマンス カウンターによって共有されるグローバル メモリのサイズをバイト単位で指定します。 既定のサイズは 524,288 バイトです。

プロパティ

名前 説明
CanRaiseEvents

コンポーネントがイベントを発生できるかどうかを示す値を取得します。

(継承元 Component)
CategoryName

このパフォーマンス カウンターのパフォーマンス カウンター カテゴリの名前を取得または設定します。

Container

IContainerを含むComponentを取得します。

(継承元 Component)
CounterHelp

このパフォーマンス カウンターの説明を取得します。

CounterName

この PerformanceCounter インスタンスに関連付けられているパフォーマンス カウンターの名前を取得または設定します。

CounterType

関連付けられているパフォーマンス カウンターのカウンターの種類を取得します。

DesignMode

Componentが現在デザイン モードであるかどうかを示す値を取得します。

(継承元 Component)
Events

この Componentにアタッチされているイベント ハンドラーの一覧を取得します。

(継承元 Component)
InstanceLifetime

プロセスの有効期間を取得または設定します。

InstanceName

このパフォーマンス カウンターのインスタンス名を取得または設定します。

MachineName

このパフォーマンス カウンターのコンピューター名を取得または設定します。

RawValue

このカウンターの生または計算されていない値を取得または設定します。

ReadOnly

この PerformanceCounter インスタンスが読み取り専用モードかどうかを示す値を取得または設定します。

Site

ISiteComponentを取得または設定します。

(継承元 Component)

メソッド

名前 説明
BeginInit()

フォームまたは別のコンポーネントで使用される PerformanceCounter インスタンスの初期化を開始します。 初期化は実行時に行われます。

Close()

パフォーマンス カウンターを閉じ、このパフォーマンス カウンター インスタンスによって割り当てられたすべてのリソースを解放します。

CloseSharedResources()

カウンターによって割り当てられたパフォーマンス カウンター ライブラリの共有状態を解放します。

CreateObjRef(Type)

リモート オブジェクトとの通信に使用されるプロキシの生成に必要なすべての関連情報を含むオブジェクトを作成します。

(継承元 MarshalByRefObject)
Decrement()

効率的なアトミック操作によって、関連するパフォーマンス カウンターを 1 つずつデクリメントします。

Dispose()

Componentによって使用されるすべてのリソースを解放します。

(継承元 Component)
Dispose(Boolean)

Componentによって使用されるアンマネージ リソースを解放し、必要に応じてマネージド リソースを解放します。

(継承元 Component)
EndInit()

フォームまたは別のコンポーネントで使用される PerformanceCounter インスタンスの初期化を終了します。 初期化は実行時に行われます。

Equals(Object)

指定したオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetLifetimeService()
古い.

このインスタンスの有効期間ポリシーを制御する現在の有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
GetService(Type)

ComponentまたはそのContainerによって提供されるサービスを表すオブジェクトを返します。

(継承元 Component)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
Increment()

効率的なアトミック操作によって、関連付けられているパフォーマンス カウンターを 1 ずつインクリメントします。

IncrementBy(Int64)

効率的なアトミック操作によって、関連付けられているパフォーマンス カウンターの値を指定した量だけインクリメントまたはデクリメントします。

InitializeLifetimeService()
古い.

このインスタンスの有効期間ポリシーを制御する有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
MemberwiseClone()

現在の Objectの簡易コピーを作成します。

(継承元 Object)
MemberwiseClone(Boolean)

現在の MarshalByRefObject オブジェクトの簡易コピーを作成します。

(継承元 MarshalByRefObject)
NextSample()

カウンター サンプルを取得し、その未処理または未計算の値を返します。

NextValue()

カウンター サンプルを取得し、その計算値を返します。

RemoveInstance()

PerformanceCounter オブジェクトInstanceNameプロパティで指定されたカテゴリ インスタンスを削除します。

ToString()

Stringの名前 (存在する場合) を含むComponentを返します。 このメソッドはオーバーライドしないでください。

(継承元 Component)

イベント

名前 説明
Disposed

コンポーネントが Dispose() メソッドの呼び出しによって破棄されるときに発生します。

(継承元 Component)

適用対象

こちらもご覧ください