MediumUsing Stopwatch in C# for Measuring Execution Time and Performance Calculations | by codezone | Stackademic
Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Member-only story

Using Stopwatch in C# for Measuring Execution Time and Performance Calculations

--

In C#, accurately measuring the execution time of code snippets and algorithms is crucial for optimizing performance. The Stopwatch class, available in the System.Diagnostics namespace, provides a reliable way to measure elapsed time with high precision. This article will guide you through the usage of the Stopwatch class for measuring execution time and performing various performance calculations in C#.

Press enter or click to view image in full size

Getting Started with Stopwatch

Before diving into complex performance evaluations, let’s start with a simple example of how to use the Stopwatch class to measure the execution time of a basic operation:

using System;
using System.Diagnostics;

class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
Console.WriteLine("Starting the stopwatch...");
stopwatch.Start();
// Simulate some operation
for (int i = 0; i < 100000000; i++) { }
stopwatch.Stop();
Console.WriteLine("Elapsed time: " + stopwatch.Elapsed);
// Reset the stopwatch for reuse
stopwatch.Reset();
Console.ReadLine();
}
}

In this example, the Stopwatch class is used to measure the time it takes to complete a loop. The Start() method begins the timer, and…

--

--

Stackademic
Stackademic

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.