How To Calculate Code Execution Time In C#

In this article, we will learn how to calculate code execution time in C#.

The StopWatch class in System.Diagnostics is used to measure the elapsed time accurately.

To optimize performance, sometimes we may have to find out the execution time of a particular segment of the C# code. For example, we may want to know how much time is taken for fetching data from the database, or reading files from the file system, or executing some business logic.

using System;
using System.Diagnostics;

namespace Execution_Time
{
    class Program
    {
        static void Main(string[] args)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 1; i <= 100; i++)
            {
                if (i == 100)
                {
                    Console.WriteLine(i);
                }
            }
            stopwatch.Stop();
            Console.WriteLine($"Execution Time: {stopwatch.ElapsedMilliseconds} Milliseconds");
            Console.WriteLine($"Execution Time: {stopwatch.Elapsed.TotalSeconds} Seconds");
            Console.WriteLine($"Execution Time: {stopwatch.Elapsed.TotalMinutes} Minutes");
        }
    }
}

In the above example, Stopwatch will return the time taken in executing the for loop. The Start() method starts measuring the time for executing the code until we call the Stop() method.

Output:

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check How To Combine Two Lists Without Duplicate Values In C#

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories