How to Measure Execution Time of Code in C#

No.of Views2069
Bookmarked0 times
Downloads 
Votes0
By  kirtan007   On  27 Jul 2010 10:07:36
Tag : CSharp , Utilities
This article demonstrates how you can find out how much time your code is taking in execution using C#.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

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.

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. 

Image Loading

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 ClassStopwatch sw = new Stopwatch();// Start The StopWatch ...From 000sw.Start();for (int i = 0; i <= 1000; i++)
            {
 
            }//Stop the Timersw.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();

 That's all. enjoy the happy code.

Sample Project Source

Download source files -38 kb

 
Sign Up to vote for this article
 
About Author
 
kirtan007
Occupation-
Company-
Member Type-Senior
Location-Not Provided
Joined date-02 Jul 2009
Home Page-http://kirtan.uni.cc
Blog Page-
He completed his Bachelor of Computer Application from Gujarat University 2009 .He is doing Master of Computer Application from Gujarat Technological University right now .. His area of Interests are Web Hacking , C# .net Windows form ,asp.net , WPF ,Silverlight ,SQL Server and Some PHP.
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top