如果您的意思是“计算处理器指令的数量”,那么没有办法做到这一点。但是,您可以非常准确地测量经过的时间。有关使用 Windows API 函数QueryPerformanceCounter在 VBA 中构造超精确秒表的详细说明,请参阅我的文章VBA 中的精确性能计时器。这是 Stopwatch 类的完整代码:
Option Explicit
Private Declare Function QueryPerformanceCounter Lib "kernel32" ( _
lpPerformanceCount As UINT64) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" ( _
lpFrequency As UINT64) As Long
Private pFrequency As Double
Private pStartTS As UINT64
Private pEndTS As UINT64
Private pElapsed As Double
Private pRunning As Boolean
Private Type UINT64
LowPart As Long
HighPart As Long
End Type
Private Const BSHIFT_32 = 4294967296# ' 2 ^ 32
Private Function U64Dbl(U64 As UINT64) As Double
Dim lDbl As Double, hDbl As Double
lDbl = U64.LowPart
hDbl = U64.HighPart
If lDbl < 0 Then lDbl = lDbl + BSHIFT_32
If hDbl < 0 Then hDbl = hDbl + BSHIFT_32
U64Dbl = lDbl + BSHIFT_32 * hDbl
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As UINT64
QueryPerformanceFrequency PerfFrequency
pFrequency = U64Dbl(PerfFrequency)
End Sub
Public Property Get Elapsed() As Double
If pRunning Then
Dim pNow As UINT64
QueryPerformanceCounter pNow
Elapsed = pElapsed + (U64Dbl(pNow) - U64Dbl(pStartTS)) / pFrequency
Else
Elapsed = pElapsed
End If
End Property
Public Sub Start()
If Not pRunning Then
QueryPerformanceCounter pStartTS
pRunning = True
End If
End Sub
Public Sub Pause()
If pRunning Then
QueryPerformanceCounter pEndTS
pRunning = False
pElapsed = pElapsed + (U64Dbl(pEndTS) - U64Dbl(pStartTS)) / pFrequency
End If
End Sub
Public Sub Reset()
pElapsed = 0
pRunning = False
End Sub
Public Sub Restart()
pElapsed = 0
QueryPerformanceCounter pStartTS
pRunning = True
End Sub
Public Property Get Running() As Boolean
Running = pRunning
End Property
将上面的代码粘贴到一个新的类模块中,并将模块命名为“秒表”。然后在代码中的其他任何地方,您都可以执行以下操作:
Sub DoStuff
Dim sw As New Stopwatch
sw.Start
myResult = SomeFunction(A, B, C)
sw.Pause
Debug.Print "SomeFunction took " & Format(sw.Elapsed * 1000, "0.000000") & " milliseconds"
End Sub