VBA中的高精度计时器

分类:代码, 博客 标签:

Excel中偶尔会用到高精度的计时器,如性能监视或统计,在一些水文应用(如水文数据查询或水文数据处理)中我们也可能非常需要了解整个程序的运行瓶颈在哪,以便有针对性地对程序进行改进,这就需要我们使用VBA调用API函数QueryFrequency与QueryCounter来实现,这里水文工具集对这些API调用进行了封装,包装为一个VBA的类,方便重复使用且易于调用。具体代码如下:

Option Explicit

'How many times per second is the counter updated?
Private Declare Function QueryFrequency Lib "kernel32" _
        Alias "QueryPerformanceFrequency" ( _
        lpFrequency As Currency) As Long

'What is the counter's value
Private Declare Function QueryCounter Lib "kernel32" _
        Alias "QueryPerformanceCounter" ( _
        lpPerformanceCount As Currency) As Long


'Variables to store the counter information
Dim mcyFrequency As Currency
Dim mcyOverhead As Currency
Dim mcyStarted As Currency
Dim mcyStopped As Currency


Private Sub Class_Initialize()
   Dim cyCount1 As Currency, cyCount2 As Currency

   'Get the counter frequency
   QueryFrequency mcyFrequency

   'Call the hi-res counter twice, to check how long it takes
   QueryCounter cyCount1
   QueryCounter cyCount2
    
   'Store the call overhead
   mcyOverhead = cyCount2 - cyCount1
End Sub


Public Sub StartTimer()
   'Get the time that you started
   QueryCounter mcyStarted
End Sub


Public Sub StopTimer()
   'Get the time that you stopped
   QueryCounter mcyStopped
End Sub


Public Property Get Elapsed() As Double
   Dim cyTimer As Currency

   'Have you stopped or not?
   If mcyStopped = 0 Then
      QueryCounter cyTimer
   Else
      cyTimer = mcyStopped
   End If

   'If you have a frequency, return the duration, in seconds
   If mcyFrequency > 0 Then
      Elapsed = (cyTimer - mcyStarted - mcyOverhead) / mcyFrequency
   End If
End Property


分类:代码, 博客 标签:

One Response to “VBA中的高精度计时器”

  1. administrative assistant  on 十一月 27th, 2010

    found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later


发表评论

You must be logged in to post a comment.