Evaluate code execution time in Csharp

Evaluate code execution time in C#

Evaluate code execution time in C#

Hello folks, sometime we as a developer wants to check exact execution time to execute our code to understand performance of our code.We can evaluate code execution time in C#. Sometime I personally could improve by understanding execution time of my code and write code again with using some optimization techniques in C#, which I will cover in some another post. You can also check my other post in which I have used StopWatch to compare execution time like Use of Yield Keyword in C#

To measure time of our code we could use System.Diagnostics.Stopwatch.

Let’s take example and understand concept instead of going more in theory.

Example – 1: 

In this example we will traverse simple 0 to 1000 and try to measure execution time of code by starting StopWatch using watch.Start(); before starting of For loop and Stop StopWatch after completing for loop using watch.Stop() and then we will print timing to measure how much time it has taken to complete execution using watch.ElapsedMilliseconds.

using System;

namespace StopwatchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new System.Diagnostics.StopWatch();
            watch.Start();

            for (int i = 0; i < 1000; i++)
                Console.Write(i);

            watch.Stop();
            Console.WriteLine($"Total Code Execution Time: {watch.ElapsedMilliseconds} ms");
        }
    }
}

Output:

Total Code Execution Time: 54 ms

**Please note execution time will totally depending on your machine configuration,  time taken may change on your machine.

Example-2:

In this particular example we will understand different methods & property from StopWatch like IsRunning and Reset(). IsRunning will check whether watch is running or not and Reset/Restart will reset watch. Below is the example which is demonstrating use of those. Let’s say sometime we will require different 3 code snippets for which we want to check  time for first two code snippet’s combined and 3rd separately execution time. To achieve this we will use below example in which we have started watch and take execution time for first two code snippet and reset StopWatch  and start again StopWatch to measure execution time of  3rd code snippet.

using System;

namespace StopwatchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            for (int i = 0; i < 1000; i++)
            {
                //Console.Write(i);
            }

            watch.Stop();

            if (!watch.IsRunning) // checks if it is not running
                watch.Start(); // Start the counter from where it stopped

            for (int j = 0; j < 1000; j++)
            {
                //Console.Write(j);
            }
            watch.Stop();

            Console.WriteLine($"Total Code for first 2 loops Execution Time: {watch.ElapsedMilliseconds} ms");

            if (!watch.IsRunning) // checks if it is not running
            {
                watch.Reset();// Reset counter
                watch.Start();// Start the counter from where it stopped
            }
            Console.WriteLine($"Total Code for 3rd loops Execution before resetting StopWatch Time: {watch.ElapsedMilliseconds} ms");

            for (int j = 0; j < 1000; j++)
            {
                //Console.Write(j);
            }

            watch.Stop();

            Console.WriteLine($"Total Code for 3rd loops Execution after resetting StopWatch Time: {watch.ElapsedMilliseconds} ms");
            Console.ReadKey();
        }
    }
}

Output:

Total Code for first 2 loops Execution Time: 216 ms
Total Code for 3rd loops Execution before resetting StopWatch Time: 0 ms
Total Code for 3rd loops Execution after resetting StopWatch Time: 194 ms

Example-3:

Most important thing of evaluating execution time of code is clean your Garbage by cleaning managed heap and memory to get exact and correct execution timing. We should use below code snippet before code snippet execution.

// Perform garbage collection.
GC.Collect();
GC.WaitForPendingFinalizers();

 

using System;

namespace StopwatchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Perform garbage collection.
            GC.Collect();
            GC.WaitForPendingFinalizers();

            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();
             
            for (int i = 0; i < 1000; i++)
            {
                //Console.Write(i);
            }
            watch.Stop();
            Console.WriteLine($"Total Code Execution Time: {watch.ElapsedMilliseconds} ms");
            Console.ReadKey();
        }
    }
}

Output:

Total Code Execution Time: 0 ms

Leave a Reply