Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

A generic benchmark routine

Total Hit ( 3369)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


You often need to benchmark a piece of code, which you usually do as follows:

Click here to copy the following block
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:

Click here to copy the following block
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


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.