Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Aug 10, 2002

A generic benchmark routine

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 benchmark
Dim 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
    MessageBox
End Enum

Function 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 elapsed
End 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
    Next
End Sub

Sub 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.")
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date