Use the Stopwatch class to time a program in C#

I often save the time with DateTime.Now and then compare it to a later time to see how much time has elapsed. The System.Diagnostics.Stopwatch class makes this a bit easier. It's Start method essentially makes the object record the current time. Later you can use the object's Stop property to make it record the elapsed time since you called Start. You can then use the object's Elapsed property to see how much time that was.

The following code how this example uses the Stopwatch class to time an operation.

private void btnCalculate_Click(object sender, EventArgs e)
    Stopwatch stopwatch = new Stopwatch();

    // Perform long calculations here.
    for (int i = 0; i < 10000000; i++)
        double x = Math.Sqrt(i);


    // Display the elapsed time.
    lblResult.Text = "Elapsed time: " +
        stopwatch.Elapsed.TotalSeconds.ToString("0.00") +
        " seconds";

The program creates a Stopwatch object and calls its Start method. It then uses a loop to waste some time. The code calls Stop and then uses Elapsed to see how much time the operation took.



What did you think of this article?

  • No trackbacks exist for this post.
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.