excel 如何在VBA中更精确地测量时间?

mpgws1up  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(156)

我有一个Excel文档,其中包含一些VBA脚本。
我使用“计时器”来测量代码的执行时间。
我无法度量向字典中添加条目所需的时间。结果为0。
有没有更精确的机制可以让我衡量这需要多长时间?

hts6caw3

hts6caw31#

在脚本的顶部,您可以添加以下内容:

Private Declare PtrSafe Function get_frequency Lib "kernel32" _
      Alias "QueryPerformanceFrequency" ( _
      ByRef Frequency As Currency) _
      As Long
 
Private Declare PtrSafe Function get_time Lib "kernel32" _
      Alias "QueryPerformanceCounter" ( _
      ByRef Counter As Currency) _
      As Long

然后在你的代码中你可以得到像这样的高精度时间测量...

' run this once
Dim per_second As Currency: get_frequency per_second

' ...

' get start time
Dim t0 As Currency: get_time t0

' HERE perform the operations you want to time 
' ...

' get end time
Dim t1 As Currency: get_time t1

' calculate high precision duration
Dim elapsed_millis As Double: elapsed_millis = (t1 - t0) / per_second * 1000#
6kkfgxo0

6kkfgxo02#

在子例程的开头添加以下内容:

Dim StartTime As Double 'Declaration of timer to identify length of runtime
StartTime = Timer

在子例程的末尾:

Debug.Print "RunTime for Program is: " & Format((Timer - StartTime) / 86400, 
"hh:mm:ss.ms") 'Print out runtime for subroutine

相关问题