Getting Code Execution Time

Ever tried doing real time performance testing for a piece of code on the basis of how much time it took to execute.
The following code will help you to get the exact time taken for a piece of code to execute.

Let's make a class and introduce a nested loop (nothing fancy as we only want to get the execution time) as in the following: 
  1. public class TestingExecutionTime  
  2. {  
  3.     public static void EngageTime()  
  4.     {  
  5.         for (int i = 0; i < 100; i++)  
  6.         {  
  7.             for (int j = 0; j < 1000; j++)  
  8.             {  
  9.                 Console.WriteLine("Loop ");  
  10.     
  11.             }  
  12.                  
  13.         }  
  14.     }  
  15. }  
In the class where you want to make a call to the above function, include the namespace "using System.Diagnostics;"
Make an object of the Stopwatch class of the Diagnostic namespace and call the previous function.

You need to follow the below steps:
  1. Reset the StopWatch
  2. Start Stopwatch
  3. Call the code
  4. Stop the Stopwatch
  5. Get Elapsed Time in the required format 
Following is the detailed code:
  1. Stopwatch stp = new Stopwatch();  
  2.   
  3.     stp.Reset();  
  4.     stp.Start();  
  5.     TestingExecutionTime.EngageTime();  
  6.     stp.Stop();  
  7.   
  8.     TimeSpan ts = stp.Elapsed;  
  9.     // Format and display the TimeSpan value.   
  10.     string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",  
  11.         ts.Hours, ts.Minutes, ts.Seconds,  
  12.         ts.Milliseconds / 10);  
  13.     Console.WriteLine(elapsedTime);  
  14.     Console.ReadKey();  
The output for the same come out to be: 00:00:07.56 
Ebook Download
View all
Learn
View all