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. }
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. stp.Reset();
  3. stp.Start();
  4. TestingExecutionTime.EngageTime();
  5. stp.Stop();
  6. TimeSpan ts = stp.Elapsed;
  7. // Format and display the TimeSpan value.
  8. string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
  9. ts.Hours, ts.Minutes, ts.Seconds,
  10. ts.Milliseconds / 10);
  11. Console.WriteLine(elapsedTime);
  12. Console.ReadKey();
The output for the same come out to be: 00:00:07.56