Redigera

Dela via


Stopwatch.Start Method

Definition

Starts, or resumes, measuring elapsed time for an interval.

public:
 void Start();
public void Start ();
member this.Start : unit -> unit
Public Sub Start ()

Examples

The following example demonstrates how to use the Start method to start a timer that measures the execution time of an application.

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

Remarks

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.

Once started, a Stopwatch timer measures the current interval, in elapsed timer ticks, until the instance is stopped or reset. Starting a Stopwatch that is already running does not change the timer state or reset the elapsed time properties.

When a Stopwatch instance measures more than one interval, the Start method resumes measuring time from the current elapsed time value. A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset. Use the Reset method before calling Start to clear the cumulative elapsed time in a Stopwatch instance. Use the Restart method to Reset and Start the Stopwatch with a single command.

Applies to

See also