Bits & Bytes

Using the C# StopWatch Class to Time Code

In order to optimize C# code, you need to be able to time sections of it to determine what is causing performance problems. The built-in Stopwatch class offers a simple solution for doing this.

The short program below demonstrates a simple example usage of the Stopwatch class. First, we create a new Stopwatch object. Then we call Start() to begin counting the time. The next section is a loop with nothing in it that runs a 1 billion times; this represents something that we would like to time. At the end of the loop, we call Stop() to record the elapsed time. Finally, we output the time at the end.

The program takes approximately 2 and a half seconds to run through the loop 1 billion times. The loop actually takes some time because it must increment the integer i and check whether it is less than 1 billion. After 1 billion times, this adds up to just a few seconds on my computer. Executing the program, yields a result like this.

StopwatchOutput

Program.cs

using System;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch qStopwatch = new Stopwatch();
        qStopwatch.Start();
        // This loop represents something that we want to time
        for (int i = 0; i < 1000000000; ++i) {
            // There is nothing here . . .
        }
        qStopwatch.Stop();

        Console.WriteLine("Elapsed Time " + qStopwatch.Elapsed);
    }
}

Tags: , , , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.