Measuring code execution time

ElektroStudios picture ElektroStudios · May 4, 2013 · Viewed 156.3k times · Source

I want to know how much time a procedure/function/order takes to finish, for testing purposes.

This is what I did but my method is wrong 'cause if the difference of seconds is 0 can't return the elapsed milliseconds:

Notice the sleep value is 500 ms so elapsed seconds is 0 then it can't return milliseconds.

    Dim Execution_Start As System.DateTime = System.DateTime.Now
    Threading.Thread.Sleep(500)

    Dim Execution_End As System.DateTime = System.DateTime.Now
    MsgBox(String.Format("H:{0} M:{1} S:{2} MS:{3}", _
    DateDiff(DateInterval.Hour, Execution_Start, Execution_End), _
    DateDiff(DateInterval.Minute, Execution_Start, Execution_End), _
    DateDiff(DateInterval.Second, Execution_Start, Execution_End), _
    DateDiff(DateInterval.Second, Execution_Start, Execution_End) * 60))

Can someone show me a better way to do this? Maybe with a TimeSpan?

The solution:

Dim Execution_Start As New Stopwatch
Execution_Start.Start()

Threading.Thread.Sleep(500)

MessageBox.Show("H:" & Execution_Start.Elapsed.Hours & vbNewLine & _
       "M:" & Execution_Start.Elapsed.Minutes & vbNewLine & _
       "S:" & Execution_Start.Elapsed.Seconds & vbNewLine & _
       "MS:" & Execution_Start.Elapsed.Milliseconds & vbNewLine, _
       "Code execution time", MessageBoxButtons.OK, MessageBoxIcon.Information)

Answer

Habib picture Habib · May 4, 2013

A better way would be to use Stopwatch, instead of DateTime differences.

Stopwatch Class - Microsoft Docs

Provides a set of methods and properties that you can use to accurately measure elapsed time.

Stopwatch stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
//your sample code
System.Threading.Thread.Sleep(500);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);