Export (0) Print
Expand All

Stopwatch Class

Provides a set of methods and properties that you can use to accurately measure elapsed time.

To browse the .NET Framework source code for this type, see the Reference Source.

System::Object
  System.Diagnostics::Stopwatch

Namespace:  System.Diagnostics
Assemblies:   System (in System.dll)
  System.Runtime.Extensions (in System.Runtime.Extensions.dll)

public ref class Stopwatch

The Stopwatch type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStopwatchInitializes a new instance of the Stopwatch class.
Top

  NameDescription
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryElapsedGets the total elapsed time measured by the current instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryElapsedMillisecondsGets the total elapsed time measured by the current instance, in milliseconds.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryElapsedTicksGets the total elapsed time measured by the current instance, in timer ticks.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryIsRunningGets a value indicating whether the Stopwatch timer is running.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetElapsedDateTimeTicksGets the high-resolution ticks as DateTime::Ticks if the system is using a high-resolution counter.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetRawElapsedTicksGets the total elapsed time, including the time since Stopwatch was last started.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryGetTimestampGets the current number of ticks in the timer mechanism.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryResetStops time interval measurement and resets the elapsed time to zero.
Public methodSupported by Portable Class LibraryRestartStops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStartStarts, or resumes, measuring elapsed time for an interval.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryStartNewInitializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryStopStops measuring elapsed time for an interval.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryFrequencyGets the frequency of the timer as the number of ticks per second. This field is read-only.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryIsHighResolutionIndicates whether the timer is based on a high-resolution performance counter. This field is read-only.
Top

NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

A Stopwatch instance is either running or stopped; use IsRunning to determine the current state of a Stopwatch. Use Start to begin measuring elapsed time; use Stop to stop measuring elapsed time. Query the elapsed time value through the properties Elapsed, ElapsedMilliseconds, or ElapsedTicks. You can query the elapsed time properties while the instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.

By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

NoteNote

On a multiprocessor computer, it does not matter which processor the thread runs on. However, because of bugs in the BIOS or the Hardware Abstraction Layer (HAL), you can get different timing results on different processors. To specify processor affinity for a thread, use the ProcessThread::ProcessorAffinity method.

The following example demonstrates how to use the Stopwatch class to determine the execution time for an application.

No code example is currently available or this language may not be supported.

The following example demonstrates the use of the Stopwatch class to calculate performance data.

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

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2015 Microsoft