Pranay Rana: Get time of Code Execution Using StopWatch

Tuesday, July 5, 2011

Get time of Code Execution Using StopWatch

During Development of the application/product or after deployment of the application/product there might be a situation where you want to find out the the how much time is taken by you code to execute ? Is it too much slow ?

Answer to this problem is make use of StopWatch class of System.Diagnostics namespace which is usefull to find out the time taken to execute given line of code. The class is helpfull to find out how efficient code develop by measuring the time of execution.

To understand how to use it consider the below demo
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//instead of this there is line of code that you are going to execute
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime);
Console.ReadLine();
Stopwatch class has method Start() and Stop(), So the as name suggest call start when you want to start your watch and call Stop when you want to stop the watch. Once you stop the watch i.e called stop method of the StopWatch class you can get the value of time of execution by using Elapsed property of the class which return TimeSpan object.

Output



There are also other important methods which are very usefull you can get the more infomation about those on the MSDN documentation over here : StopWatch Class
Methods
StartNew - Initializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.
Restart - Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
Reset - Stops time interval measurement and resets the elapsed time to zero.

Properties
ElapsedMilliseconds - Gets the total elapsed time measured by the current instance, in milliseconds.
ElapsedTicks - Gets the total elapsed time measured by the current instance, in timer ticks.

Advantage
  • Easy and Simple to use.
  • Useful when want to find out the time take by the line of code to execute.
  • By using the class there is no need of any third party tool because it part of the .net framework.

1 comment: