22 Aug

C# Calculate Execution Time

This example shows how much time takes a procedure/function/code. It is useful for micro-benchmarks in code optimization. To do this, We use the Stopwatch class in System.Diagnostics namespace.

Sample Code:

            // Create stopwatch
            Stopwatch stopwatch = new Stopwatch();

            // Begin timing

            // Do something
            for (int i = 0; i < 10; i++)

            // Stop timing

            // Write result
            Console.WriteLine("Total Time: {0}", stopwatch.ElapsedMilliseconds);

Leave a Reply

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