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:
- public class TestingExecutionTime
- {
- public static void EngageTime()
- {
- for (int i = 0; i < 100; i++)
- {
- for (int j = 0; j < 1000; j++)
- {
- Console.WriteLine("Loop ");
-
- }
-
- }
- }
- }
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:
- Reset the StopWatch
- Start Stopwatch
- Call the code
- Stop the Stopwatch
- Get Elapsed Time in the required format
Following is the detailed code:
- Stopwatch stp = new Stopwatch();
-
- stp.Reset();
- stp.Start();
- TestingExecutionTime.EngageTime();
- stp.Stop();
-
- TimeSpan ts = stp.Elapsed;
-
- string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
- ts.Hours, ts.Minutes, ts.Seconds,
- ts.Milliseconds / 10);
- Console.WriteLine(elapsedTime);
- Console.ReadKey();
The output for the same come out to be: 00:00:07.56