ARTICLE

Measure Execution Time of Code in C#

Posted by Kirtan Patel Articles | How do I November 03, 2009
This article demonstrates how you can find out how much time your code is taking in execution using C#.
Reader Level:
Download Files:
 

Introduction

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 :)



Login to add your contents and source code to this article
post comment
     

thanks

Posted by Hapani ANkit Feb 28, 2013

Cool !!! I don't know that there are easy ways to check it. Thanks !!!

Posted by kevin tun Oct 19, 2012

Cool !!! I don't know that there are easy ways to check it. Thanks !!!

Posted by kevin tun Oct 19, 2012

thanks you so much !

Posted by quyen suki May 06, 2011

Thanks. Thanks for the technical perspective in solution.

Posted by Kavinga Gunasekara Jun 17, 2010
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts