Friday, May 25, 2012

Measure Execution time using Stopwatch class


Measure Execution time using Stopwatch class

Many a times we will have situations where we need to evaluate the performance of a function or a piece of code, Performance in the database can be measured using tools like SQL Profiler and other tools, but when it comes to the .Net code, we need to evaluate the time elapsed to execute the code.


In .Net the System.Diagnostics Namespace provides a Stopwatch class, which can be used to measure the time elapsed to execute a code. This class provides Start() and Stop() methods, we need to place the code to be evaluated between these functions to measure the execution time.

Stopwatch timer = new Stopwatch();
timer.Start();
    
//Code to be Evaluated Goes Here.
timer.Stop();

timer.ElapsedMilliseconds.ToString() – Gives the time taken to execute the code in Milliseconds.

Example
Let us measure the time taken to load a DropDownList with 1000 items; here is the code to evaluate the performance using the Stopwatch class.

Stopwatch timer;
timer = new Stopwatch();
timer.Start();

objConn = new SqlConnection(strConnectionString);
strQuery = "SELECT ID, Name FROM Employee";
objCmd = new SqlCommand(strQuery, objConn);
objDA = new SqlDataAdapter(objCmd);
dsEmployee = new DataSet();
objDA.Fill(dsEmployee, "dtEmployee");

drpEmployee.DataSource = dsEmployee.Tables["dtEmployee"];
drpEmployee.DataTextField = "Name";
drpEmployee.DataValueField = "ID";
drpEmployee.DataBind();

timer.Stop();
lblExecutionTime.Text = timer.ElapsedMilliseconds.ToString();

That’s it we have used the Stopwatch class to measure the time taken to load a DropDownList with 1000 items.

Search Flipkart Products:
Flipkart.com

No comments: