PerformanceCounter.NextValue メソッド

定義

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

public:
 float NextValue();
public float NextValue ();
member this.NextValue : unit -> single
Public Function NextValue () As Single

戻り値

Single

このカウンターのためにシステムで取得された計算される値の次の値。

例外

インスタンスがパフォーマンス カウンターに正しく関連付けられていません。

システム API にアクセス中にエラーが発生しました。

管理特権を使用せずに実行されているコードがパフォーマンス カウンターの読み取りを試みました。

次のコード例では、カウンターを ElapsedTime 作成し、メソッドを NextValue 使用して一定期間にわたってカウンターの値を表示します。

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

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 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 ( !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.",
                PerformanceCounterCategoryType.SingleInstance, CCDC);
            // Return, rerun the application to make use of the new counters.
            return;
        }
        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("++++++++++++++++++++++");
    }
}

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

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.", _
                   PerformanceCounterCategoryType.SingleInstance, 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(ByVal 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

注釈

注意

カウンターの計算値が 2 つのカウンター読み取りに依存する場合、最初の読み取り操作は 0.0 を返します。 パフォーマンス カウンターのプロパティをリセットして別のカウンターを指定することは、新しいパフォーマンス カウンターを作成することと同じであり、新しいプロパティを使用した最初の読み取り操作では 0.0 が返されます。 カウンターが次の増分読み取りを NextValue 実行できるようにするために、メソッドの呼び出し間の推奨遅延時間は 1 秒です。

注意

パフォーマンス カウンターを読み取る場合は、管理者特権が必要です。 Windows Vista では、ユーザー アカウント制御 (UAC: User Account Control) でユーザーの権限が決定されます。 ユーザーが組み込みの Administrators グループのメンバーである場合、そのユーザーには標準ユーザー アクセス トークンおよび管理者アクセス トークンの 2 つのランタイム アクセス トークンが割り当てられています。 既定では、ユーザーは標準ユーザー ロールに所属します。 パフォーマンス カウンターにアクセスするコードを実行するには、まず特権を標準ユーザーから管理者に昇格させる必要があります。 この操作は、アプリケーションの起動時にアプリケーション アイコンを右クリックし、管理者として実行することを指定して行うことができます。

適用対象