Firstly, I did not design this piece of code. I have it in my collection of nice pieces. All the credit must go to the person who created. I found it in many places...
Try this and compare results, please:
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function getFrequency Lib "kernel32" Alias _
"QueryPerformanceFrequency" (cyFrequency As Currency) As Long
Private Declare PtrSafe Function getTickCount Lib "kernel32" Alias _
"QueryPerformanceCounter" (cyTickCount As Currency) As Long
#Else
Private Declare Function getFrequency Lib "kernel32" Alias _
"QueryPerformanceFrequency" (cyFrequency As Currency) As Long
Private Declare Function getTickCount Lib "kernel32" Alias _
"QueryPerformanceCounter" (cyTickCount As Currency) As Long
#End If
Public Function MicroTimer() As Double
' returns seconds from Windows API calls (high resolution timer)
Dim cyTicks1 As Currency, cyTicks2 As Currency
Static cyFrequency As Currency
MicroTimer = 0
If cyFrequency = 0 Then getFrequency cyFrequency
' get ticks
getTickCount cyTicks1
getTickCount cyTicks2
' calc seconds
If cyFrequency Then MicroTimer = cyTicks2 / cyFrequency
End Function
And use it in the next way:
Sub teste_tempo()
Dim i As Long, dTime As Double
dTime = MicroTimer
For i = 0 To 100000000
i = i + 1
Next i
MsgBox (MicroTimer - dTime) * 1000 & " [ms]"
End Sub
But, it will never return exactly the same passed time!. The Window processed load your CPU and RAM in different percentages for different moments. The differences will be smaller and smaller inverse proportional with the iterations number.