Sometimes you may need to find out how much time a piece of code takes in execution. This is very important when an application is slow. By using this approach, you may find out what code takes how much time.
Platform
----------
.net 2.0/3.0/3.5
Language :
------------
C#
What this code will do?
-------------------------------
Code will measure how much time particular code statements takes to execute.
Implementation
----------------------
First of all all, import this namespace.
using System.Diagnostics;
Now we are using StopWatch class to measure the time taken by the code.
This is how the UI looks like. Download the attached project.
Most of the code is commented in this project so you can understand easily.
private void btnGetExecutionTime_Click(object sender, EventArgs e)
{
//First Create the instance of Stopwatch Class
Stopwatch sw = new Stopwatch();
// Start The StopWatch ...From 000
sw.Start();
for (int i = 0; i <= 1000; i++)
{
}
//Stop the Timer
sw.Stop();
//Writing Execution Time in label
string ExecutionTimeTaken = string.Format("Minutes :{0}\nSeconds :{1}\n Mili seconds :{2}",sw.Elapsed.Minutes,sw.Elapsed.Seconds,sw.Elapsed.TotalMilliseconds);
label1.Text = ExecutionTimeTaken;
}
Now whatever code you write between Start and Stop methods, that you can find out using Elapsed.
Now, you can use StopWatch to check other code. Just Reset the StopWatch using Reset method.
sw.Reset();
Thank you :)
Comments are Expected :)

vinayak SheregarPosted Jan 16, 2014, 2:00 AM
Cool thanks
Hapani ANkitPosted Feb 28, 2013, 2:51 AM
thanks
kevin tunPosted Oct 19, 2012, 5:50 AM
Cool !!! I don't know that there are easy ways to check it. Thanks !!!
kevin tunPosted Oct 19, 2012, 5:50 AM
Cool !!! I don't know that there are easy ways to check it. Thanks !!!
quyen sukiPosted May 6, 2011, 12:16 PM
thanks you so much !
Kavinga GunasekaraeditedPosted Jun 15, 2010, 7:24 AMEdited Jun 15, 2010, 7:26 AM
First this post help to get idea about code execution time. So this seems it counts time for that for loop. In this case can we include this start() and stop() between codes which referring methods from another separate class file. In that case will this stopwatch give execution time for whole process? public Class B { method B1{//some code here} } class A { Stopwatch sw = new Stopwatch(); sw.Start(); B bObj=new B(); for (int i = 0; i <= 1000; i++) { bObj.B1() } sw.Stop(); } In this case it gives the correct execution time? Order of using code correct? (Stop watch start after Creating the object or it should count that time too?) Can you please explain this?
Altaf KhatriPosted Dec 8, 2009, 2:15 PM
Is there a way in Visual studio 2008 to see the execution time for each method. Since visual studio already has a stack trace, the only thing needed is the execution time along with it? http://www.altafkhatri.com/