.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Measure Execution Time of Code in C#

Posted By:Kirtan       Posted Date: April 21, 2010    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

article will teach you how to find out how much time your code is taking in execution using C#.


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.


.net 2.0/3.0/3.5

Language :


What this code will do?

Code will measure how much time particular code statements takes to execute.


First of all all, import this name space. 

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

    for (int i = 0; i <= 1000; i++)


    //Stop the Timer

    //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.


Another approach for measuring code Execution time is to Note Down the DateTime.Now before the execution and after the

Execution but StopWatch Approach will be more accurate than this DateTime.Now Approach.

Thank you :)

Download The Sample Code

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend