How to measure function execution time in C#

1 Answer

0 votes
// Measuring function execution time in 
// C# using a reusable Timer (milliseconds + seconds)

using System;
using System.Diagnostics;

public class MeasureTimeWithTimer
{
    // ---------------------------
    // Reusable Timer class
    // ---------------------------
    public class Timer
    {
        private Stopwatch sw;

        // Start the timer
        public void Start() {
            sw = Stopwatch.StartNew();
        }

        // Stop the timer
        public void Stop() {
            sw.Stop();
        }

        // Return elapsed time in milliseconds
        public double ElapsedMilliseconds() {
            return sw.Elapsed.TotalMilliseconds;
        }

        // Return elapsed time in seconds
        public double ElapsedSeconds() {
            return sw.Elapsed.TotalSeconds;
        }
    }

    // ---------------------------
    // Function to measure
    // ---------------------------
    static void Work()
    {
        long sum = 0;
        for (long i = 0; i < 100_000_000; i++)
            sum += i;
    }

    // ---------------------------
    // Main program
    // ---------------------------
    public static void Main()
    {
        Timer t = new Timer();

        t.Start();
        Work();
        t.Stop();

        double ms = t.ElapsedMilliseconds();
        double sec = t.ElapsedSeconds();

        Console.WriteLine("Execution time: " + ms + " ms");
        Console.WriteLine("Execution time: " + sec + " seconds");
    }
}



/* 
run:

Execution time: 115.7143 ms
Execution time: 0.1157143 seconds

*/

 



answered May 27 by avibootz
...