Elapsed Time Calculation In C#

When our code is running slowly or takes a long time to complete, it is necessary to measure the time spent by various code operations such as validations, database calls, external API requests, and so on.

This article’s main focus will be on using a stopwatch to track the amount of time that has passed in C#.NET Core code so that we can calculate how long each action of the code will take.

Using System.Diagnostics.Stopwatch Class

The System.Diagnostic namespace contains the Stopwatch class, which may be used to accurately quantify how long code operations take to execute.

This Stopwatch class is essentially a simulation or implementation of a stopwatch.

The Stopwatch class has methods and attributes useful for precise measurement for every logical block in the code.

Here is the code for the console program that shows how to use a stopwatch to measure the duration of time.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ProCodeGuide.Sample.Async
    public class Program
        static readonly Stopwatch timer = new Stopwatch();
        public static async Task Main(string[] args)

            Console.WriteLine("Program Start - " + timer.Elapsed.ToString());

            await PerformValidationsAsync();
            Console.WriteLine("Validation Performed - " + timer.Elapsed.ToString());

            await GetDataFromAPIAsync();
            Console.WriteLine("Got Data from API - " + timer.Elapsed.ToString());

            await SaveToDBAsync();
            Console.WriteLine("Saved to DB - " + timer.Elapsed.ToString());


        private static async Task PerformValidationsAsync()
            await Task.Delay(2000);

        private static async Task GetDataFromAPIAsync()
            await Task.Delay(3000);

        private static async Task SaveToDBAsync()
            await Task.Delay(5000);

In C#.NET, you must call the start method on the stopwatch class at the point from which you want to begin timing the passage of time, such as the start of a method, a network call, or a database save. Once you reach the part of the code where you wish to stop keeping track of time, you must then use the stop method. After that, you can use the elapsed property to see how much time has passed between the calls to start and stop.

As seen by the code above, you can use the elapsed property of the stopwatch class to evaluate the amount of time that has passed since that point in the code even when the stopwatch is running. The elapsed time will progressively rise when the stopwatch is started until it is stopped.

The output seen in the console window after running the aforementioned code is as follows.

You may also utilize the ElapsedMilliseconds or ElapsedTicks properties, which return the elapsed time as Milliseconds or Ticks, respectively, instead of the stopwatch’s Elapsed property, which returns a TimeSpan.You can pass the TimeSpan instance to another method or class that requires one as well as format the TimeSpan instance into a text format for printing or logging.

Use the Stopwatch class instead of the standard DateTime class to measure execution time because it produces more accurate results. To clear the cumulative elapsed time of an existing stopwatch object, utilize the reset function of the stopwatch class. For example, if you begin measuring elapsed time in the code for a network call, once the network call is completed and elapsed time has been logged for that operation, you can reset the stopwatch elapsed time to measure elapsed time for the next logical block of code, which could be a database call or another network call, and so on.

Using the code below, you may format elapsed time as Hours, Minutes, and Seconds.

Console.WriteLine("Saved to DB - {0:hh\\:mm\\:ss}",timer.Elapsed);

The format string was used in the following code to format the elapsed time in hh, mm, and ss format. This style is excellent for tasks that take a long time to complete.

Submit a Comment

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


Select Categories