You often need to benchmark a piece of code, which you usually do as follows:
Dim start As Date = Now' insert here the code to benchmarkDim elapsed As TimeSpan = Now.Subtract(start)Console.WriteLine("Total time: {0} secs.", elapsed)
Thanks to delegates, you can write a reusable routine that can benchmark any Sub that takes zero arguments. This generic benchmark routine returns the TimeSpan value and optionally displays a default or a custom message, either on the console window or in a message box:
Delegate Sub BenchmarkDelegate()Enum BenchmarkModes DontShow Console MessageBoxEnd EnumFunction BenchmarkIt(ByVal routine As BenchmarkDelegate, _ ByVal mode As BenchmarkModes, Optional ByVal msg As String = Nothing) As _ TimeSpan ' remember starting time Dim start As Date = Now ' run the procedure to be benchmarked routine.Invoke() ' evaluate elapsed time, assign to result Dim elapsed As TimeSpan = Now.Subtract(start) ' exit if nothing else to do If mode = BenchmarkModes.DontShow Then Return elapsed ' build a suitable string if none was provided If msg Is Nothing OrElse msg.Length = 0 Then ' use the name of the target method msg = routine.Method.Name End If ' append a placeholder for elapsed time, if not there If msg.IndexOf("{0}") < 0 Then msg &= ": {0} secs" End If ' display on the console window or a message box If mode = BenchmarkModes.Console Then Console.WriteLine(msg, elapsed) ElseIf mode = BenchmarkModes.MessageBox Then MessageBox.Show(String.Format(msg, elapsed)) End If ' return result to caller Return elapsedEnd Function
Here’s an example that benchmarks an array fill routine and displays the result on the console window. Notice that we pass Nothing as the msg argument, and the routine uses the name of the target method as the default:
Sub ArrayFill() Dim i As Integer Dim arr(100000) As Integer For i = 0 To UBound(arr) arr(i) = i NextEnd SubSub Main() BenchmarkIt(AddressOf ArrayFill, BenchmarkModes.Console)End Sub
In this second example, we display the elapsed time with a custom message in a message box:
BenchmarkIt(AddressOf ArrayFill, BenchmarkModes.MessageBox, _ "Array filling takes {0} seconds.")