简体   繁体   中英

VBA efficiency test

I found a VBA code to test the run time of a code in the thread How do you test running time of VBA code? . I implemented and it worked. But every time I run a simple code, as below,it returns me a different result.

I searched and tested many codes, but didn't found what I was expecting.

Is there a way of test the code and return something like the number of clocks that the code demands? Something that every time I run with the code below, returns me the same value?

Sub teste_tempo()

    Dim eficiencia As New Ctimer
    eficiencia.StartCounter

    For i = 0 To 10
        i = i + 1
    Next i
    MsgBox eficiencia.TimeElapsed & "[ms]"

End Sub

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM