DCSIMG
How to measure elapsed time in C# with Stopwatch class - Michael Neiter's Blog

How to measure elapsed time in C# with Stopwatch class

Published 01 April 09 10:00 AM | Michael Neiter

In this post I will discuss how to measure elapsed time in C# with Stopwatch class.

What is a Stopwatch:

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

In a simple scenario we call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

Stopwatch class depends on the hardware available in your computer and implements the high-resolution performance counter API functions of Windows.

Example:

The following example shows how to create Stopwatch object, call the Start method,  call the Stop method, call the Reset method and then to check the elapsed time using the Elapsed property.

Stopwatch sw = new Stopwatch();

sw.Start();

// Do something here

sw.Stop();

Console.WriteLine("Time elapsed: {0}ms", sw.Elapsed.TotalMilliseconds.ToString());

sw.Reset();

sw.Start();

// Do something here 

sw.Stop();

Console.WriteLine("Time elapsed: {0}ms", sw.Elapsed.TotalMilliseconds.ToString());

Console.ReadLine();
 
Summary:
 
Stopwatch class is an effective tool to use when performing diagnostics or benchmarks on an application.

Reference:
 

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: