[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use the Stopwatch class to time a program in C#

[Use the Stopwatch class to time a program in C#]

To measure elapsed time, you can save the current time with DateTime.Now and then compare it to a later time to see how much time has elapsed. The Stopwatch class in the System.Diagnostics namespace 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 passed.

This example uses the following code time an operation.

using System.Diagnostics; ... private void btnCalculate_Click(object sender, EventArgs e) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // Perform long calculations here. for (int i = 0; i < 100000000; i++) { double x = Math.Sqrt(i); } stopwatch.Stop(); // 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.

You can use Start again to make the watch resume timing if you have stopped it. For example, you can use that feature to time an operation that starts and stops.

The Stopwatch class also provides a few other methods to make using it easier. The Reset method stops the watch and resets it to zero. The Restart method stops the watch, resets it to zero, and then starts it again.

Note that the Stopwatch class has been around since .NET Framework 2 (Visual Studio 2005), but the Restart method was only introduced in .NET Framework 4 (Visual Studio 2010). That means you can't use Restart with earlier versions of C#. Use Reset followed by Start instead.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.