Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


marking time in vb

Posted on 2000-04-18
Medium Priority
Last Modified: 2012-08-14
i want to mark time to as much precision
as possible.  how do i do it in vb?

Question by:senardji
LVL 18

Expert Comment

ID: 2727599
Dim dStart As Double

dStart = Timer
MsgBox "!"
Debug.Print Timer - dStart


Expert Comment

ID: 2727613
   Private Declare Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
    Private Type SYSTEMTIME
        wYear As Integer
        wMonth As Integer
        wDayOfWeek As Integer
        wDay As Integer
        wHour As Integer
        wMinute As Integer
        wSecond As Integer
        wMilliseconds As Integer
    End Type
    Dim TimeUnformatted As SYSTEMTIME


    GetSystemTime TimeUnformatted
    MsgBox TimeUnformatted.wMilliseconds

The above code will do an API call to get the system time broken down into the user defined data type SYSTEMTIME.  At that point you can work with timestamps down to the millisecond level.

Hope this helps.
LVL 12

Expert Comment

ID: 2727628
Although you'll find a lot of controls denominating time in units of Ms you'll find that in reality there is no underlying timer mechanism that will provide a timer tick any tighter than the 18.2Hz time-of-day tick. This gives you a granularity of about 55Ms. Any control that says it can measure time tighter than this on a plain (no special hardware) PC is simply *LYING* to you.

There will be several that will attack this answer, but I've got the original IBM technical reference manual at my elbow and both complete schematics and BIOS listings and no-one has *EVER* proved me wrong on this - and many have tried.

PC's cannot measure time tighter than 55Ms. Period.

You *CAN* add specialty hardware to do it. You can by timer counter cards or tap into the sound card hardware, but on a *plain PC*, no, nope, noway, nohow.


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.


Expert Comment

ID: 2728412
Singles or Doubles are no good for precision because they get screwed up in their binary representations when copied to memory. (try formatting a few to see). For the best precision possible with VB set your variables that hold your numbers to Variant Type and sub type them using the CDec Function in order to use the Decimal Data Type. Like this:

Milliseconds = CDec(TicksorWhatever)

This data type is good to about 24 decimal places and stays uncorrupted since it is represented in memory as Integers. Also, another trick is to clear the floating point registers of your processor by calling something like D = Int(D) just before doing any floating point math.

Hope this helps,

Accepted Solution

mathies earned 200 total points
ID: 2729155
Look that:

' ============================================================================
' Module:    CTimer
'   Stopwatch type timer class
' Notes:
' ----------------------------------------------------------------------------
' History:
'   07/--/1999  web  initial version
' ============================================================================
Option Explicit

Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Private Declare Function timeGetDevCaps Lib "winmm.dll" (lpTimeCaps As TIMECAPS, ByVal uSize As Long) As Long
Private Declare Function timeBeginPeriod Lib "winmm.dll" (ByVal uPeriod As Long) As Long
Private Declare Function timeEndPeriod Lib "winmm.dll" (ByVal uPeriod As Long) As Long

Private Type TIMECAPS
   wPeriodMin As Long
   wPeriodMax As Long
End Type

Private Const TIMER_STOPPED = 0
Private Const TIMER_RUNNING = 1
Private Const PERIOD_NOT_SET = 0

' multimedia timer constants adapted from MMSYSTEM.H

Private Const TIMERR_BASE = 96
Private Const TIMERR_NOERROR = 0                    ' no error
Private Const TIMERR_NOCANDO = TIMERR_BASE + 1      ' request not completed
Private Const TIMERR_STRUCT = TIMERR_BASE + 33      ' time struct size

Private mlngStartTime       As Long
Private mlngAccumulatedTime As Long
Private mlngRunning         As Long
Private mlngPeriod          As Long
Private mtcPeriods          As TIMECAPS

Private Sub Class_Initialize()

    mlngRunning = TIMER_RUNNING         ' the timer starts up running
    mlngPeriod = PERIOD_NOT_SET

    ' get the min & max periods at initialization since they don't change

    timeGetDevCaps mtcPeriods, Len(mtcPeriods)

    ' reset the timer to start cleanly


End Sub

Private Sub Class_Terminate()

    ' make sure the timer period is released

    If mlngPeriod <> PERIOD_NOT_SET Then
        timeEndPeriod mlngPeriod
    End If

End Sub

' properties

' ElapsedTime - return the time elapsed since the timer was last reset

Public Property Get ElapsedTime() As Long

    ElapsedTime = mlngAccumulatedTime - mlngStartTime + timeGetTime() * mlngRunning

End Property

Public Property Get MinPeriod() As Long

    MinPeriod = mtcPeriods.wPeriodMin

End Property

Public Property Get MaxPeriod() As Long

    MaxPeriod = mtcPeriods.wPeriodMax

End Property

Public Property Get Period() As Long

    Period = mlngPeriod

End Property

' methods

' BeginPeriod - set timing period

Public Sub BeginPeriod(Period As Long)
    Dim lngReturnCode   As Long

    If mlngPeriod <> PERIOD_NOT_SET Then
        Err.Raise 51, "CStopWatchMM.BeginPeriod", "Period is already set, EndPeriod call required first"
    End If

    With mtcPeriods
        If Period < .wPeriodMin Then
            Err.Raise 51, "CStopWatchMM.BeginPeriod", "Period less than minimum"
        End If
        If Period > .wPeriodMax Then
            Err.Raise 51, "CStopWatchMM.BeginPeriod", "Period greater than maximum"
        End If
    End With

    lngReturnCode = timeBeginPeriod(Period)

    If lngReturnCode = TIMERR_NOERROR Then
        mlngPeriod = Period
        mlngPeriod = PERIOD_NOT_SET
        Err.Raise 51, "CStopWatchMM.BeginPeriod", "Error setting the multimedia timer period"
    End If

End Sub

' EndPeriod - release timing period

Public Sub EndPeriod(Period As Long)
    Dim lngReturnCode   As Long

    If mlngPeriod = PERIOD_NOT_SET Then
        Err.Raise 51, "CStopWatchMM.EndPeriod", "Period not set, BeginPeriod call required first"
    End If

    ' period must match the BeginPeriod call

    If Period <> mlngPeriod Then
        Err.Raise 51, "CStopWatchMM.EndPeriod", "Period does not match call to BeginPeriod"
    End If

    lngReturnCode = timeEndPeriod(Period)

    mlngPeriod = PERIOD_NOT_SET

    If lngReturnCode <> TIMERR_NOERROR Then
        Err.Raise 51, "CStopWatchMM.EndPeriod", "Error releasing the multimedia timer period"
    End If

End Sub

' Reset - reset the timer to zero (does not change the running state)

Public Sub Reset()
    mlngAccumulatedTime = 0
    mlngStartTime = timeGetTime()

End Sub

' StartTiming - restart the timer (after StopTiming) and accumulate time

Public Sub StartTiming()

    If mlngRunning = 0 Then
        mlngStartTime = timeGetTime()
        mlngRunning = TIMER_RUNNING
    End If

End Sub

' StopTiming - stop the timer so time doesn't accumulate

Public Sub StopTiming()

    If mlngRunning <> 0 Then
        mlngAccumulatedTime = mlngAccumulatedTime + timeGetTime() - mlngStartTime
        mlngStartTime = 0
        mlngRunning = TIMER_STOPPED
    End If

End Sub
LVL 12

Expert Comment

ID: 2730377
Mathies solution looks good but (as I said originally) is dependent on the presence of the sound card to support the multi-media functions. While this is certainly a common enough peripherial, it is not on 100% of the machines out in the world...


Expert Comment

ID: 2734321
If you want to have more details on how develop more precision timer.
Go to www.vbpj.com and look the article
of april 2000 on timer and you will found all the information how to build you timer.

There no much manner to use timer.
1) The vb timer control
2) API timer control. But It`s only   give you the same precision than the VB control but you don`t need a form to use it.
3) The answer I gave you before.

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Suggested Courses
Course of the Month14 days, 21 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question