#24 – Use Stopwatch Class to Determine the Execution Time for an C# Application

Stopwatch class provides a set of methods and properties that you can use to accurately measure elapsed time.

The following example demonstrates how to use the Stopwatch class to determine the execution time for an application.

using System;
using System.Diagnostics;
using System.Threading;

Stopwatch sw = new Stopwatch();

// Begin Timing

// Do sth.
for (int i = 0; i < 2; i++)

// End Timing

// Elapsed
var elapsed = sw.Elapsed;

Console.WriteLine($"Time elapsed (raw): {elapsed}");

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
    elapsed.Hours, elapsed.Minutes, elapsed.Seconds,
    elapsed.Milliseconds / 10);
Console.WriteLine($"Time elapsed (formated): {elapsedTime}");

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.