I need to calculate the difference between two timestamps in milliseconds. Unfortunatley, the DateDiff-function of VBA does not offer this precision. Are there any workarounds?
Thanks in advance!
I need to calculate the difference between two timestamps in milliseconds. Unfortunatley, the DateDiff-function of VBA does not offer this precision. Are there any workarounds?
Thanks in advance!
You can use the method described here
Other methods describe use of the VBA Timer function but this is only accurate to one hundredth of a second (centisecond).
Besides the Method described by AdamRalph (GetTickCount()
), you can do this:
QueryPerformanceCounter()
and QueryPerformanceFrequency()
API FunctionsIf you just need time elapsed in Centiseconds then you don't need the TickCount API. You can just use the VBA.Timer Method which is present in all Office products.
Public Sub TestHarness()
Dim fTimeStart As Single
Dim fTimeEnd As Single
fTimeStart = Timer
SomeProcedure
fTimeEnd = Timer
Debug.Print Format$((fTimeEnd - fTimeStart) * 100!, "0.00 "" Centiseconds Elapsed""")
End Sub
Public Sub SomeProcedure()
Dim i As Long, r As Double
For i = 0& To 10000000
r = Rnd
Next
End Sub
GetTickCount and Performance Counter are required if you want to go for micro seconds.. For millisenconds you can just use some thing like this..
'at the bigining of the module
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
Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
'In the Function where you need find diff
Dim sSysTime As SYSTEMTIME
Dim iStartSec As Long, iCurrentSec As Long
GetLocalTime sSysTime
iStartSec = CLng(sSysTime.wSecond) * 1000 + sSysTime.wMilliseconds
'do your stuff spending few milliseconds
iCurrentSec=CLng(sSysTime.wSecond) * 1000 + sSysTime.wMilliseconds
'Different between iStartSec and iCurrentSec will give you diff in MilliSecs