你如何testingVBA代码的运行时间?

有没有代码在VBA我可以包装一个function,这将让我知道所花费的时间,以便我可以比较不同的运行时间的function?

除非你的function非常慢,否则你将需要一个非常高分辨率的定时器。 我知道的最准确的是QueryPerformanceCounter 。 谷歌它的更多信息。 尝试将以下内容放到一个类中,称为CTimer ,然后可以在全局某个地方创build一个实例,然后调用.StartCounter.TimeElapsed

 Option Explicit Private Type LARGE_INTEGER lowpart As Long highpart As Long End Type Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long Private m_CounterStart As LARGE_INTEGER Private m_CounterEnd As LARGE_INTEGER Private m_crFrequency As Double Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256# Private Function LI2Double(LI As LARGE_INTEGER) As Double Dim Low As Double Low = LI.lowpart If Low < 0 Then Low = Low + TWO_32 End If LI2Double = LI.highpart * TWO_32 + Low End Function Private Sub Class_Initialize() Dim PerfFrequency As LARGE_INTEGER QueryPerformanceFrequency PerfFrequency m_crFrequency = LI2Double(PerfFrequency) End Sub Public Sub StartCounter() QueryPerformanceCounter m_CounterStart End Sub Property Get TimeElapsed() As Double Dim crStart As Double Dim crStop As Double QueryPerformanceCounter m_CounterEnd crStart = LI2Double(m_CounterStart) crStop = LI2Double(m_CounterEnd) TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency End Property 

VBA中的计时器function可以让您自午夜以来的秒数达到1/100秒。

 Dim t as single t = Timer 'code MsgBox Timer - t 

如果你需要更高的分辨率,我只需要运行1000次函数,并把总时间除以1000。

如果您尝试像秒表一样返回时间,则可以使用以下API返回系统启动后的时间(以毫秒为单位):

 Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Sub testTimer() Dim t As Long t = GetTickCount For i = 1 To 1000000 a = a + 1 Next MsgBox GetTickCount - t, , "Milliseconds" End Sub 

http://www.pcreview.co.uk/forums/grab-time-milliseconds-included-vba-t994765.html (因为winmm.dll中的timeGetTime不适合我,而QueryPerformanceCounter对于所需的任务来说太复杂了)

我们已经在winmm.dll中使用了一个基于timeGetTime的解决scheme,这个解决scheme已经有很多年了。 见http://www.aboutvb.de/kom/artikel/komstopwatch.htm

这篇文章是德文的,但下载的代码(包装dll函数调用的VBA类)很简单,不需要阅读文章就可以使用和理解。