Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time elapsed in milliseconds

Since performance of string concatenation is quite weak in VB6 I'm testing several StringBuilder implementations. To see how long they're running, I currently use the built-in

Timer

function which only gives me the number of seconds that have passed after midnight.

Is there a way (I guess by importing a system function) to get something with milliseconds precision?

like image 688
RobertB Avatar asked Jul 02 '09 08:07

RobertB


2 Answers

Yes, you can use the Win32 API:

DWORD WINAPI GetTickCount(void);

To import it in VB6 declare it like this:

Private Declare Function GetTickCount Lib "kernel32" () As Long

Call it before the operation and after and then calculate the difference in time passed.

like image 117
justadreamer Avatar answered Sep 20 '22 01:09

justadreamer


Put the following code in a Stopwatch class:

Option Explicit

Private Declare Function QueryPerformanceCounter Lib "Kernel32" (X As Currency) As Boolean
Private Declare Function QueryPerformanceFrequency Lib "Kernel32" (X As Currency) As Boolean

Private m_startTime As Currency
Private m_freq As Currency
Private m_overhead As Currency

Public Sub start()
    QueryPerformanceCounter m_startTime
End Sub

Public Function ElapsedSeconds() As Double
    Dim currentTime As Currency
    QueryPerformanceCounter currentTime
    ElapsedSeconds = (currentTime - m_startTime - m_overhead) / m_freq
End Function

Public Function ElapsedMilliseconds() As Double
    ElapsedMilliseconds = ElapsedSeconds * 1000
End Function

Private Sub Class_Initialize()
    QueryPerformanceFrequency m_freq
    Dim ctr1 As Currency
    Dim ctr2 As Currency
    QueryPerformanceCounter ctr1
    QueryPerformanceCounter ctr2
    m_overhead = ctr2 - ctr1
End Sub

You can use it as follows:

Dim sw as StopWatch
Set sw = New StopWatch
sw.Start

' Code you want to time

Debug.Print "Code took " & sw.ElapsedMilliseconds " ms"
like image 35
Patrick McDonald Avatar answered Sep 19 '22 01:09

Patrick McDonald