How to Measure execution time in C#

  1. By using Stopwatch Class in C#, you can get measure process time.

This Requires System.Diagnostics name space.
This might need to be converted from milliseconds to other unit.

using System;
using System.Diagnostics;

public class Example
{
    public static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
 
        stopwatch.Start();
        /*
        Your code blocks to measure:
        */
        stopwatch.Stop();
 
        Console.WriteLine("Elapsed Time is {0} ms", stopwatch.ElapsedMilliseconds);
    }
}

2. By using TimeSpan

using System;
using System.Diagnostics;
using System.Threading;
 
public class Example
{
    public static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
 
        stopwatch.Start();
        /*
        Your code blocks to measure:
        */
        stopwatch.Stop();
 
        TimeSpan ts = stopwatch.Elapsed;
 
        Console.WriteLine("Elapsed Time is {0:00}:{1:00}:{2:00}.{3}",
                        ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
    }
}

Leave a Reply