< Previous lesson | Table of Content | Content of this Chapter | Next lesson >

Timer in Visual Basic

Now you will design your own class and use it as your own object. Remember that class and object are actually the same things. You design a Class. When you want to use that class, it is called Object of that class.

To access the data inside the class, you can use either Let Property or Get Property, and when you want to make Method of the class, simply make Public type Sub procedure or Function.

1. Start with new Standard Exe project
2. In the Project window, do right click and in the popup menu that appear, select Add > Class Module and Open new class
3. Change the Name property of that class into MyLibrary
4. We will create one property and two methods. Add the following code to the class general declaration:


Private startTIME As Single 'to count the elapse time
Public Property Get PI() As Double
PI = 3.14159265358979
'Pi=3.1415926535897932384626433832795
End Property
'TimeStart and TimeEnd is a couple procedure
'to know how long a procedure is done
Public Sub TimeStart()
startTIME = Timer
End Sub

Public Sub TimeEnd()
' report elapse time from the SetStartTime using msgBox
' User use this procedure in couple with SetStartTime
MsgBox "Elapse time: " & CalcElapseTime
End Sub

Private Function CalcElapseTime() As String
Dim TimeEnd As Single, elapseTime As Single
Dim reportTime As String
TimeEnd = Timer ' Set end time.
elapseTime = TimeEnd - startTIME ' Calculate total time.
'report and formating the time
If elapseTime > 60 Then
If elapseTime > 3600 Then
reportTime = _
Format(elapseTime \ 3600, "0") & " h: " & _
Format((elapseTime Mod 3600) \ 60, "0") & " m: " & _
Format(elapseTime - ((elapseTime \ 60) * 60), "0.000") & " s"
Else
reportTime = _
Format(elapseTime \ 60, "0") & " min: " & _
Format(elapseTime - (elapseTime \ 60) * 60, "0.000") & " sec."
End If
Else
reportTime = Format(elapseTime, "0.000") & " seconds"
End If
CalcElapseTime = reportTime
End Function
5. Now we are ready to use our new class. We define a variable as that class with keyword New to create new object of that class. In the form declaration section type (try to type it manually):
Private num As Integer
Private lib As New MyLibrary

6. Then type manually (do not copy and paste) the following code in Form Click event procedure:

Private Sub Form_Click()
num = num + 1
If num Mod 2 = 1 Then
lib.TimeStart
Else
lib.TimeEnd
End If
End Sub


7. Run the program and click the form two times to see how long the times elapse between the two clicks.
8. Do not forget to Save the project as MyLibrary Project.

You use the TimeStart and TimeEnd to check how long it takes to process your own procedure. In this way, you can distinguish which procedure takes the longest time and replace those codes with the better one.

< Previous lesson | Table of Content | Content of this Chapter | Next lesson >