Simple Performance Measurement Tool Stopwatch

Stopwatch is an excellent class in the System.Diagnostics namespace that allows a simple execution time measurement. It is extremely accurate and handy when other, more complex monitoring tools are not available or are just not needed for the sake of simplicity.

This built-in class was introduced in .Net framework 2.0 and is suited for several scenarios. It helps you to optimize your code, to choose among several possible solutions or to determine a performance spike.

Now we're going to take a closer look at how to use Stopwatch properly.

Stopwatch in action

Before we can even start using this class in our solution, we need to add the corresponding namespace.

  1. using System.Diagnostics;  
the Next step is to create an object instance of the class.
  1. Stopwatch stopwatch = new Stopwatch();  

Now, everything is set and we can start measuring the time. We start the measurement by calling the Start method that internally saves the current time. To stop it, we call the Stop method. Of course, there should be some long-lasting action between these two that we want to monitor.

  1. // Begin timing  
  2. stopwatch.Start();  
  3.   
  4. // Do something  
  5. // Long running process  
  6.   
  7. // Stop timing  
  8. stopwatch.Stop();  
Once the measurement is over, there are the following three properties available to check the elapsed time.
 
1.Elapsed: gets the total elapsed time by the current Stopwatch instance as a TimeSpan (for example 00:00:00.0000024).
  1. // Write result  
  2. Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);  
2. ElapsedMilliseconds: gets the total elapsed time in milliseconds.
  1. // Write result  
  2. Console.WriteLine("Time elapsed: {0}", stopwatch.ElapsedMilliseconds);  
3. ElapsedTicks: gets the total elapsed time in timer ticks. 
  1. // Write result  
  2. Console.WriteLine("Time elapsed: {0}", stopwatch.ElapsedTicks);  
To eliminate and simplify your code, you can also call the static StartNew method to create a new instance and start it right away.
  1. var stopwatch = Stopwatch.StartNew();  

Summary

Stopwatch is an easy to use tool that measures the execution time of a desired process/action. It helps to optimize the code in scenarios where the time plays an important role. 


Similar Articles