Stopwatch Třída

Definice

Poskytuje sadu metod a vlastností, které můžete použít k přesnému měření uplynulého času.

public ref class Stopwatch
public class Stopwatch
type Stopwatch = class
Public Class Stopwatch
Dědičnost
Stopwatch

Příklady

Následující příklad ukazuje, jak použít Stopwatch třídu k určení doby spuštění aplikace.

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

Následující příklad ukazuje použití Stopwatch třídy k výpočtu dat o výkonu.

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;

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

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

void TimeOperations()
{
   Int64 nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch::Frequency;
   const long numIterations = 10000;
   
   // Define the operation title names.
   array<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.
      Int64 numTicks = 0;
      Int64 numRollovers = 0;
      Int64 maxTicks = 0;
      Int64 minTicks = Int64::MaxValue;
      int indexFastest = -1;
      int indexSlowest = -1;
      Int64 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++ )
      {
         Int64 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", 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", 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-10001.
            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 );

   }
}

int main()
{
   DisplayTimerProperties();
   Console::WriteLine();
   Console::WriteLine( "Press the Enter key to begin:" );
   Console::ReadLine();
   Console::WriteLine();
   TimeOperations();
}
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

Poznámky

Instance Stopwatch může měřit uplynulý čas v jednom intervalu nebo celkový součet uplynulého času v několika intervalech. V typickém Stopwatch scénáři zavoláte metodu Start , nakonec zavoláte metodu Stop a pak pomocí vlastnosti zkontrolujete uplynulý čas Elapsed .

Instance Stopwatch je spuštěná nebo zastavená. Slouží IsRunning k určení aktuálního stavu objektu Stopwatch. Použijte Start k zahájení měření uplynulého času; použijte Stop k zastavení měření uplynulého času. Dotaz na hodnotu uplynulého času prostřednictvím vlastností Elapsed, ElapsedMillisecondsnebo ElapsedTicks. Pokud je instance spuštěná nebo zastavená, můžete se dotazovat na vlastnosti uplynulého času. Vlastnosti uplynulého času se neustále zvyšují, zatímco Stopwatch je spuštěna; zůstávají konstantní, když je instance zastavena.

Ve výchozím nastavení se hodnota Stopwatch uplynulého času instance rovná součtu všech měřených časových intervalů. Každé volání začne Start počítat v kumulativním uplynulé době; každé volání Stop ukončí měření aktuálního intervalu a zablokuje kumulativní hodnotu uplynulého času. Reset Pomocí metody vymažte kumulativní uplynulý čas v existující Stopwatch instanci.

Mírami Stopwatch uplynulého času počítání odškrtnutí časovače v základním mechanismu časovače. Pokud nainstalovaný hardware a operační systém podporují čítač výkonu s vysokým rozlišením, pak Stopwatch třída používá tento čítač k měření uplynulého času. V opačném Stopwatch případě třída používá k měření uplynulého času systémový časovač. Frequency Pomocí polí a IsHighResolution určete přesnost a rozlišení Stopwatch implementace časování.

Třída Stopwatch pomáhá manipulovat s čítači výkonu souvisejícími s časováním v rámci spravovaného kódu. Konkrétně Frequency lze pole a GetTimestamp metodu použít místo nespravovaných QueryPerformanceFrequency rozhraní API systému Windows a QueryPerformanceCounter.

Poznámka

Na víceprocesorovém počítači nezáleží na tom, na kterém procesoru vlákno běží. Kvůli chybám v systému BIOS nebo vrstvě HAL (Hardware Abstraction Layer) však můžete získat různé výsledky časování na různých procesorech. Pokud chcete určit spřažení procesoru pro vlákno, použijte metodu ProcessThread.ProcessorAffinity .

Konstruktory

Stopwatch()

Inicializuje novou instanci Stopwatch třídy.

Pole

Frequency

Získá frekvenci časovače jako počet zaškrtnutí za sekundu. Toto pole je jen ke čtení.

IsHighResolution

Označuje, jestli je časovač založen na čítači výkonu s vysokým rozlišením. Toto pole je jen ke čtení.

Vlastnosti

Elapsed

Získá celkový uplynulý čas měřený aktuální instancí.

ElapsedMilliseconds

Získá celkový uplynulý čas měřený aktuální instancí v milisekundách.

ElapsedTicks

Získá celkový uplynulý čas měřený aktuální instancí v odškrtávkách časovače.

IsRunning

Získá hodnotu označující, zda Stopwatch je časovač spuštěn.

Metody

Equals(Object)

Určí, zda se zadaný objekt rovná aktuálnímu objektu.

(Zděděno od Object)
GetElapsedTime(Int64)

Získá uplynulý čas od startingTimestamp načtení hodnoty pomocí GetTimestamp().

GetElapsedTime(Int64, Int64)

Získá uplynulý čas mezi dvěma časovými razítky načtenými pomocí GetTimestamp().

GetHashCode()

Slouží jako výchozí hashovací funkce.

(Zděděno od Object)
GetTimestamp()

Získá aktuální počet zaškrtnutí v mechanismu časovače.

GetType()

Získá aktuální Type instanci.

(Zděděno od Object)
MemberwiseClone()

Vytvoří mělkou kopii aktuálního Objectsouboru .

(Zděděno od Object)
Reset()

Zastaví měření časového intervalu a obnoví uplynulý čas na nulu.

Restart()

Zastaví měření časového intervalu, obnoví uplynulý čas na nulu a začne měřit uplynulý čas.

Start()

Spustí nebo obnoví měření uplynulého času v intervalu.

StartNew()

Inicializuje novou Stopwatch instanci, nastaví vlastnost uplynulý čas na nulu a začne měřit uplynulý čas.

Stop()

Zastaví měření uplynulého času pro interval.

ToString()

Elapsed Vrátí čas jako řetězec.

ToString()

Vrátí řetězec, který představuje aktuální objekt.

(Zděděno od Object)

Platí pro

Viz také