関数のさまざまな実行時間を比較できるように、実行にかかった時間を知らせる関数をラップできる VBA のコードはありますか?
8 に答える
関数が非常に遅い場合を除き、非常に高解像度のタイマーが必要になります。私が知っている最も正確なものはQueryPerformanceCounter
. 詳細については、Google で検索してください。以下をクラスにプッシュしてみてください。それを呼び出すと、CTimer
グローバルな場所にインスタンスを作成して呼び出すことができます.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 の Timer 関数を使用すると、午前 0 時からの経過秒数を 1/100 秒まで取得できます。
Dim t as single
t = Timer
'code
MsgBox Timer - t
ストップウォッチのように時間を返したい場合は、システムの起動からの時間をミリ秒単位で返す次の 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が必要なタスクには複雑すぎたため)
初心者向けに、これらのリンクは、時間監視したいすべての潜水艦の自動プロファイリングを行う方法を説明しています:
http://www.nullskull.com/a/1602/profiling-and-optimizing-vba.aspx
http://sites.mcpher.com/share/Home/excelquirks/optimizationlink http://sites.mcpher.com/share/Home/excelquirks/downlable-items の procProfiler.zip を参照してください。
何年もの間、ミリ秒の精度でwinmm.dllのtimeGetTimeに基づくソリューションを使用してきました。http://www.aboutvb.de/kom/artikel/komstopwatch.htmを参照してください
記事はドイツ語ですが、ダウンロードのコード(dll関数呼び出しをラップするVBAクラス)は、記事を読まなくても使用および理解できるほど単純です。