How to calculate code execution time in C#

By FoxLearn 2/7/2025 3:39:34 AM   154
To calculate the code execution time in C#, you can use the Stopwatch class from the System.Diagnostics namespace.

This class allows you to accurately measure how long a specific block of code takes to execute, making it ideal for performance profiling and optimization.

Example 1: Using Stopwatch to Measure Loop Execution Time

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Create and start the stopwatch
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Code block whose execution time we want to measure
        for (int i = 0; i < 1000; i++)
        {
            // Some code
            Console.Write(i);
        }

        // Stop the stopwatch
        stopwatch.Stop();

        // Output the execution time in milliseconds
        Console.WriteLine($"\nExecution Time: {stopwatch.ElapsedMilliseconds} ms");
    }
}

Output:

Execution Time: 100 ms

In this example:

  1. We create an instance of Stopwatch.
  2. The Start() method begins measuring time.
  3. The Stop() method ends the measurement.
  4. The ElapsedMilliseconds property gives the total time in milliseconds that the code took to execute.

The output time may vary depending on the system's performance and workload.

Example 2: Using StartNew to Start the Stopwatch Immediately

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Initialize and start the stopwatch in one step
        Stopwatch stopwatch = Stopwatch.StartNew();

        // Code block whose execution time we want to measure
        for (int i = 0; i < 1000; i++)
        {
            // Some code
            Console.Write(i);
        }

        // Stop the stopwatch
        stopwatch.Stop();

        // Output the execution time in milliseconds
        Console.WriteLine($"\nExecution Time: {stopwatch.ElapsedMilliseconds} ms");
    }
}

Output:

Execution Time: 100 ms

Here, Stopwatch.StartNew() simplifies initialization by both creating and starting the stopwatch in one line.

Example 3: Measuring Time for Multiple Code Segments

var watch = System.Diagnostics.Stopwatch.StartNew();

for (int i = 0; i < 1000; i++)
{
    Console.Write(i);
}

watch.Stop();

// some other code here...

if (!watch.IsRunning)  // Check if stopwatch is not running
    watch.Start();     // Start the stopwatch again from where it stopped

for (int j = 0; j < 100; j++)
{
    Console.Write(j);
}

watch.Stop();

Console.WriteLine($"Total Execution Time: {watch.ElapsedMilliseconds} ms");

Output:

Total Execution Time: 130 ms

In this case:

  • We check whether the stopwatch is already stopped using IsRunning.
  • If it isn't running, we restart it using Start(), and the stopwatch resumes measuring time from the point it was stopped.

Example 4: Measuring Time for Each Code Segment

var watch = System.Diagnostics.Stopwatch.StartNew();

for (int i = 0; i < 1000; i++)
{
    Console.Write(i);
}

watch.Stop();

Console.WriteLine($"Loop 1 Execution Time: {watch.ElapsedMilliseconds} ms");

// some code here...

if (!watch.IsRunning)
    watch.Restart();  // Resets and starts the stopwatch again

for (int j = 0; j < 100; j++)
{
    Console.Write(j);
}

watch.Stop();

Console.WriteLine($"Loop 2 Execution Time: {watch.ElapsedMilliseconds} ms");

Output:

Loop 1 Execution Time: 100 ms
Loop 2 Execution Time: 30 ms

In this example:

  • After the first loop, we use the Restart() method to reset the stopwatch and start fresh. This allows us to measure the execution time of separate code segments independently using the same Stopwatch instance.

Key Methods in Stopwatch:

  • Start(): Begins measuring elapsed time.
  • Stop(): Stops the stopwatch and freezes the current elapsed time.
  • StartNew(): Initializes and starts the stopwatch in a single line.
  • Restart(): Resets the stopwatch and starts measuring time from zero again.
  • ElapsedMilliseconds: Retrieves the total elapsed time in milliseconds.

Using the Stopwatch class in C# is an efficient and accurate way to measure the execution time of code blocks.