To measure execution time in C#, substract start and end datetime.

         public void MeasureTime()
        {

            // Capture start time
            DateTime startDateTime = DateTime.Now;

            // Do something for 1000ms...
            Thread.Sleep(1000);

            // Capture end time
            DateTime endDateTime = DateTime.Now;

            // Determine duration
            TimeSpan duration = endDateTime - startDateTime;

            // Show duration
            Console.WriteLine(string.Format("Hours{0} Minutes{1} Seconds {2}, Milliseconds{3}",duration.Hours, duration.Minutes, duration.Seconds,duration.Milliseconds));
        }

One Comment

  1. Of beter nog, gebruik de stopwatch uit System.Diagnostics:

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

    // Begin timing
    stopwatch.Start();

    // Do something
    Thread.Sleep(1000);

    // Stop timing
    stopwatch.Stop();

    // Write result
    Console.WriteLine(“Time elapsed: {0}”, stopwatch.Elapsed);

    Gerben

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.