基准VBA代码

aev*_*nko 13 excel optimization benchmarking vba

什么被认为是最准确的基准VBA代码的方法(在我的情况下,我在Excel中测试代码)?除了下面的2之外,还有其他任何基准代码的技术吗?如果有的话,该方法的优点/缺点是什么?

这是两种流行的方法.

第一:计时器

Sub TimerBenchmark()

Dim benchmark As Double
benchmark = Timer

'Do your code here

MsgBox Timer - benchmark

End Sub
Run Code Online (Sandbox Code Playgroud)

Tick(我认为这是最准确的):

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

Sub TickBenchmark()

Dim Start As Long
Dim Finish As Long

Start = GetTickCount()

'Do your code here

Finish = GetTickCount()
MsgBox CStr((Finish - Start) / 1000)

End Sub
Run Code Online (Sandbox Code Playgroud)

Ron*_*son 15

以下代码使用比Excel更准确的Windows函数.它取自http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_MakingWorkbooksCalculateFaster.同一页面还包含一些有关提高Excel 2007性能的重要提示.

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

Function MicroTimer() As Double

  'Returns seconds.

  Dim cyTicks1 As Currency
  Static cyFrequency As Currency
  MicroTimer = 0

  ' Get frequency.
  If cyFrequency = 0 Then getFrequency cyFrequency

  ' Get ticks.
  getTickCount cyTicks1                            

  ' Seconds
  If cyFrequency Then MicroTimer = cyTicks1 / cyFrequency 
End Function
Run Code Online (Sandbox Code Playgroud)

  • @StockB FWIW,在`Declare`和`Function`之间添加`PtrSafe`,用于在64位MS Office中声明API函数. (3认同)
  • 该作者的作者是Stackoverflow的定期撰稿人.他自己的网站有更多关于Excel和性能的精彩信息:http://www.decisionmodels.com/ (2认同)

JMa*_*Max 6

有趣的问题.这不是一个完整的答案,但这太长了,不能作为评论发布.
我用的是这种程序:

Option Explicit
Public Time As Double
Sub Chrono()
If Time = 0 Then
    Time = Now()
Else
    MsgBox "Total time :" & Application.Text(Now() - _
        Time, "mm:ss") & "."  'or whatever if not a msgbox
    Time = 0
End If
End Sub
Run Code Online (Sandbox Code Playgroud)

这样,您可以将代码放在任何地方,只需要调用两次(例如):

If C_DEBUG Then Call Chrono
Run Code Online (Sandbox Code Playgroud)

在您要测试的代码部分的开头和结尾处.

然而,我会说没有真正的"准确"方法,因为它还取决于你的计算机上运行的是什么.我会说这些方法主要有助于说明哪个代码比另一个更好.