次の方法で共有


Stopwatch クラス

定義

経過時間を正確に測定するために使用できる一連のメソッドとプロパティを提供します。

public ref class Stopwatch
public class Stopwatch
type Stopwatch = class
Public Class Stopwatch
継承
Stopwatch

次の例では、 Stopwatch クラスを使用して、アプリケーションの実行時間を決定する方法を示します。

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}
Imports System.Diagnostics
Imports System.Threading

Class Program

    Shared Sub Main(ByVal args() As String)
        Dim stopWatch As New Stopwatch()
        stopWatch.Start()
        Thread.Sleep(10000)
        stopWatch.Stop()
        ' Get the elapsed time as a TimeSpan value.
        Dim ts As TimeSpan = stopWatch.Elapsed

        ' Format and display the TimeSpan value.
        Dim elapsedTime As String = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
        Console.WriteLine( "RunTime " + elapsedTime)

    End Sub
End Class

次の例では、 Stopwatch クラスを使用してパフォーマンス データを計算する方法を示します。

using System;
using System.Diagnostics;

namespace StopWatchSample
{
    class OperationsTimer
    {
        public static void Main()
        {
            DisplayTimerProperties();

            Console.WriteLine();
            Console.WriteLine("Press the Enter key to begin:");
            Console.ReadLine();
            Console.WriteLine();

            TimeOperations();
        }

        public static void DisplayTimerProperties()
        {
            // Display the timer frequency and resolution.
            if (Stopwatch.IsHighResolution)
            {
                Console.WriteLine("Operations timed using the system's high-resolution performance counter.");
            }
            else
            {
                Console.WriteLine("Operations timed using the DateTime class.");
            }

            long frequency = Stopwatch.Frequency;
            Console.WriteLine("  Timer frequency in ticks per second = {0}",
                frequency);
            long nanosecPerTick = (1000L*1000L*1000L) / frequency;
            Console.WriteLine("  Timer is accurate within {0} nanoseconds",
                nanosecPerTick);
        }

        private static void TimeOperations()
        {
            long nanosecPerTick = (1000L*1000L*1000L) / Stopwatch.Frequency;
            const long numIterations = 10000;

            // Define the operation title names.
            String [] operationNames = {"Operation: Int32.Parse(\"0\")",
                                           "Operation: Int32.TryParse(\"0\")",
                                           "Operation: Int32.Parse(\"a\")",
                                           "Operation: Int32.TryParse(\"a\")"};

            // Time four different implementations for parsing
            // an integer from a string.

            for (int operation = 0; operation <= 3; operation++)
            {
                // Define variables for operation statistics.
                long numTicks = 0;
                long numRollovers = 0;
                long maxTicks = 0;
                long minTicks = Int64.MaxValue;
                int indexFastest = -1;
                int indexSlowest = -1;
                long milliSec = 0;

                Stopwatch time10kOperations = Stopwatch.StartNew();

                // Run the current operation 10001 times.
                // The first execution time will be tossed
                // out, since it can skew the average time.

                for (int i=0; i<=numIterations; i++)
                {
                    long ticksThisTime = 0;
                    int inputNum;
                    Stopwatch timePerParse;

                    switch (operation)
                    {
                        case 0:
                            // Parse a valid integer using
                            // a try-catch statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            try
                            {
                                inputNum = Int32.Parse("0");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.

                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 1:
                            // Parse a valid integer using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            if (!Int32.TryParse("0", out inputNum))
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 2:
                            // Parse an invalid value using
                            // a try-catch statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            try
                            {
                                inputNum = Int32.Parse("a");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 3:
                            // Parse an invalid value using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            if (!Int32.TryParse("a", out inputNum))
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;

                        default:
                            break;
                    }

                    // Skip over the time for the first operation,
                    // just in case it caused a one-time
                    // performance hit.
                    if (i == 0)
                    {
                        time10kOperations.Reset();
                        time10kOperations.Start();
                    }
                    else
                    {

                        // Update operation statistics
                        // for iterations 1-10000.
                        if (maxTicks < ticksThisTime)
                        {
                            indexSlowest = i;
                            maxTicks = ticksThisTime;
                        }
                        if (minTicks > ticksThisTime)
                        {
                            indexFastest = i;
                            minTicks = ticksThisTime;
                        }
                        numTicks += ticksThisTime;
                        if (numTicks < ticksThisTime)
                        {
                            // Keep track of rollovers.
                            numRollovers ++;
                        }
                    }
                }

                // Display the statistics for 10000 iterations.

                time10kOperations.Stop();
                milliSec = time10kOperations.ElapsedMilliseconds;

                Console.WriteLine();
                Console.WriteLine("{0} Summary:", operationNames[operation]);
                Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks",
                    indexSlowest, numIterations, maxTicks);
                Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks",
                    indexFastest, numIterations, minTicks);
                Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds",
                    numTicks / numIterations,
                    (numTicks * nanosecPerTick) / numIterations );
                Console.WriteLine("  Total time looping through {0} operations: {1} milliseconds",
                    numIterations, milliSec);
            }
        }
     }
}
Imports System.Diagnostics

Class OperationsTimer

   Public Shared Sub Main()
      DisplayTimerProperties()

      Console.WriteLine()
      Console.WriteLine("Press the Enter key to begin:")
      Console.ReadLine()
      Console.WriteLine()

      TimeOperations()
   End Sub

   Public Shared Sub DisplayTimerProperties()

      ' Display the timer frequency and resolution.
      If Stopwatch.IsHighResolution Then
         Console.WriteLine("Operations timed using the system's high-resolution performance counter.")
      Else
         Console.WriteLine("Operations timed using the DateTime class.")
      End If

      Dim frequency As Long = Stopwatch.Frequency
      Console.WriteLine("  Timer frequency in ticks per second = {0}", frequency)
      Dim nanosecPerTick As Long = 1000000000 / frequency
      Console.WriteLine("  Timer is accurate within {0} nanoseconds", nanosecPerTick)

   End Sub

   Private Shared Sub TimeOperations()

      Dim nanosecPerTick As Long = 1000000000 / Stopwatch.Frequency
      Const numIterations As Long = 10000

      ' Define the operation title names.
      Dim operationNames As String() =  _
        {"Operation: Int32.Parse(""0"")", _
         "Operation: Int32.TryParse(""0"")", _
         "Operation: Int32.Parse(""a"")", _
         "Operation: Int32.TryParse(""a"")"}

      ' Time four different implementations for parsing
      ' an integer from a string.

      Dim operation As Integer
      For operation = 0 To 3
         ' Define variables for operation statistics.
         Dim numTicks As Long = 0
         Dim numRollovers As Long = 0
         Dim maxTicks As Long = 0
         Dim minTicks As Long = Int64.MaxValue
         Dim indexFastest As Integer = - 1
         Dim indexSlowest As Integer = - 1
         Dim milliSec As Long = 0

         Dim time10kOperations As Stopwatch = Stopwatch.StartNew()

         ' Run the current operation 10001 times.
         ' The first execution time will be tossed
         ' out, since it can skew the average time.
         Dim i As Integer
         For i = 0 To numIterations
            Dim ticksThisTime As Long = 0
            Dim inputNum As Integer
            Dim timePerParse As Stopwatch

            Select Case operation
               Case 0
                  ' Parse a valid integer using
                  ' a try-catch statement.
                  ' Start a new stopwatch timer.
                  timePerParse = Stopwatch.StartNew()

                  Try
                     inputNum = Int32.Parse("0")
                  Catch e As FormatException
                     inputNum = 0
                  End Try

                  ' Stop the timer, and save the
                  ' elapsed ticks for the operation.
                  timePerParse.Stop()
                  ticksThisTime = timePerParse.ElapsedTicks
               Case 1
                  ' Parse a valid integer using
                  ' the TryParse statement.
                  ' Start a new stopwatch timer.
                  timePerParse = Stopwatch.StartNew()

                  If Not Int32.TryParse("0", inputNum) Then
                     inputNum = 0
                  End If

                  ' Stop the timer, and save the
                  ' elapsed ticks for the operation.
                  timePerParse.Stop()
                  ticksThisTime = timePerParse.ElapsedTicks
               Case 2
                  ' Parse an invalid value using
                  ' a try-catch statement.
                  ' Start a new stopwatch timer.
                  timePerParse = Stopwatch.StartNew()

                  Try
                     inputNum = Int32.Parse("a")
                  Catch e As FormatException
                     inputNum = 0
                  End Try

                  ' Stop the timer, and save the
                  ' elapsed ticks for the operation.
                  timePerParse.Stop()
                  ticksThisTime = timePerParse.ElapsedTicks
               Case 3
                  ' Parse an invalid value using
                  ' the TryParse statement.
                  ' Start a new stopwatch timer.
                  timePerParse = Stopwatch.StartNew()

                  If Not Int32.TryParse("a", inputNum) Then
                     inputNum = 0
                  End If

                  ' Stop the timer, and save the
                  ' elapsed ticks for the operation.
                  timePerParse.Stop()
                  ticksThisTime = timePerParse.ElapsedTicks

               Case Else
            End Select

            ' Skip over the time for the first operation,
            ' just in case it caused a one-time
            ' performance hit.
            If i = 0 Then
               time10kOperations.Reset()
               time10kOperations.Start()
            Else

               ' Update operation statistics
               ' for iterations 1-10001.
               If maxTicks < ticksThisTime Then
                  indexSlowest = i
                  maxTicks = ticksThisTime
               End If
               If minTicks > ticksThisTime Then
                  indexFastest = i
                  minTicks = ticksThisTime
               End If
               numTicks += ticksThisTime
               If numTicks < ticksThisTime Then
                  ' Keep track of rollovers.
                  numRollovers += 1
               End If
            End If
         Next i

         ' Display the statistics for 10000 iterations.
         time10kOperations.Stop()
         milliSec = time10kOperations.ElapsedMilliseconds

         Console.WriteLine()
         Console.WriteLine("{0} Summary:", operationNames(operation))
         Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks", _
            indexSlowest, numIterations, maxTicks)
         Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks", _
            indexFastest, numIterations, minTicks)
         Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds", _
            numTicks / numIterations, numTicks * nanosecPerTick / numIterations)
         Console.WriteLine("  Total time looping through {0} operations: {1} milliseconds", _
            numIterations, milliSec)
      Next operation

   End Sub
End Class

注釈

Stopwatch インスタンスは、1 つの間隔の経過時間、または複数の間隔にわたる経過時間の合計を測定できます。 一般的な Stopwatch シナリオでは、 Start メソッドを呼び出し、最終的に Stop メソッドを呼び出した後、 Elapsed プロパティを使用して経過時間を確認します。

Stopwatch インスタンスが実行中または停止中です。IsRunningを使用して、Stopwatchの現在の状態を確認します。 Startを使用して経過時間の測定を開始します。経過時間の測定を停止するには、Stopを使用します。 ElapsedElapsedMilliseconds、またはElapsedTicksのプロパティを使用して経過時間の値を照会します。 インスタンスの実行中または停止中に、経過時間プロパティに対してクエリを実行できます。 経過時間プロパティは、 Stopwatch の実行中に着実に増加します。インスタンスが停止しても一定のままです。

既定では、 Stopwatch インスタンスの経過時間値は、測定されたすべての時間間隔の合計と等しくなります。 Startへの各呼び出しは累積経過時間でカウントを開始します。Stopの各呼び出しは、現在の間隔の測定を終了し、累積経過時間の値を固定します。 既存のStopwatch インスタンスの累積経過時間をクリアするには、Reset メソッドを使用します。

Stopwatchは、基になるタイマー メカニズムのタイマー ティックをカウントすることによって経過時間を測定します。 インストールされているハードウェアとオペレーティング システムが高解像度のパフォーマンス カウンターをサポートしている場合、 Stopwatch クラスはそのカウンターを使用して経過時間を測定します。 それ以外の場合、 Stopwatch クラスはシステム タイマーを使用して経過時間を測定します。 FrequencyフィールドとIsHighResolution フィールドを使用して、Stopwatchタイミング実装の精度と解像度を決定します。

Stopwatch クラスは、マネージド コード内でのタイミング関連のパフォーマンス カウンターの操作を支援します。 具体的には、アンマネージド Windows API QueryPerformanceFrequencyQueryPerformanceCounterの代わりに、Frequency フィールドとGetTimestamp メソッドを使用できます。

マルチプロセッサ コンピューターでは、スレッドが実行されているプロセッサは関係ありません。 ただし、BIOS またはハードウェア抽象化レイヤー (HAL) のバグにより、異なるプロセッサで異なるタイミング結果を得ることができます。 スレッドのプロセッサ アフィニティを指定するには、 ProcessThread.ProcessorAffinity メソッドを使用します。

コンストラクター

名前 説明
Stopwatch()

Stopwatch クラスの新しいインスタンスを初期化します。

フィールド

名前 説明
Frequency

タイマーの頻度を 1 秒あたりのティック数として取得します。 このフィールドは読み取り専用です。

IsHighResolution

タイマーが高解像度パフォーマンス カウンターに基づいているかどうかを示します。 このフィールドは読み取り専用です。

プロパティ

名前 説明
Elapsed

現在のインスタンスによって測定された合計経過時間を取得します。

ElapsedMilliseconds

現在のインスタンスによって測定された合計経過時間をミリ秒単位で取得します。

ElapsedTicks

現在のインスタンスによって測定された合計経過時間をタイマー ティック単位で取得します。

IsRunning

Stopwatch タイマーが実行されているかどうかを示す値を取得します。

メソッド

名前 説明
Equals(Object)

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

(継承元 Object)
GetElapsedTime(Int64, Int64)

GetTimestamp()を使用して取得された 2 つのタイムスタンプ間の経過時間を取得します。

GetElapsedTime(Int64)

GetTimestamp()を使用して取得したstartingTimestamp値以降の経過時間を取得します。

GetHashCode()

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

(継承元 Object)
GetTimestamp()

タイマー メカニズムの現在のティック数を取得します。

GetType()

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

(継承元 Object)
MemberwiseClone()

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

(継承元 Object)
Reset()

時間間隔の測定を停止し、経過時間を 0 にリセットします。

Restart()

時間間隔の測定を停止し、経過時間をゼロにリセットし、経過時間の測定を開始します。

Start()

間隔の経過時間を測定して開始または再開します。

StartNew()

新しい Stopwatch インスタンスを初期化し、経過時間プロパティを 0 に設定して、経過時間の測定を開始します。

Stop()

間隔の経過時間の測定を停止します。

ToString()

Elapsed時刻を文字列として返します。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

適用対象

こちらもご覧ください