2013-06-12 126 views
0

我有一個帶有很多循環的「大」vba程序,現在我想要計算每個步驟對應程序的各個命令,當我啓動它時,所以也許我可以找到至少不是真正高性能的循環。我想要執行一些步驟。計算程序步驟

現在任何人都知道這是如何工作?或者在Excel2010中已經存在一些這樣的功能?

Thx。我知道我的恩裏克語不是很好。 >。 <

編輯13年6月14日 現在我把它寫,所以我的模塊中

Sub DoStuff() 
Dim sw As New Stopwatch 
sw.Start 
Call pranlesen.plan_gen 
sw.Pause 
Debug.Print "SomeFunction took " & format(sw.Elapsed * 1000, "0.000000") & " milliseconds" 
End Sub 

類是正確稱爲秒錶,我不知道有什麼缺陷。

回答

2

如果您的意思是「計算處理器指令的數量」,否則沒有辦法做到這一點。但是,您可以非常準確地測量已用時間。有關使用Windows API功能QueryPerformanceCounter在VBA中構建超精確秒錶的詳細說明,請參見我的文章Accurate Performance Timers in VBA。下面是秒錶類的完整代碼:

Option Explicit 

Private Declare Function QueryPerformanceCounter Lib "kernel32" (_ 
    lpPerformanceCount As UINT64) As Long 
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (_ 
    lpFrequency As UINT64) As Long 

Private pFrequency As Double 
Private pStartTS As UINT64 
Private pEndTS As UINT64 
Private pElapsed As Double 
Private pRunning As Boolean 

Private Type UINT64 
    LowPart As Long 
    HighPart As Long 
End Type 

Private Const BSHIFT_32 = 4294967296# ' 2^32 

Private Function U64Dbl(U64 As UINT64) As Double 
    Dim lDbl As Double, hDbl As Double 
    lDbl = U64.LowPart 
    hDbl = U64.HighPart 
    If lDbl < 0 Then lDbl = lDbl + BSHIFT_32 
    If hDbl < 0 Then hDbl = hDbl + BSHIFT_32 
    U64Dbl = lDbl + BSHIFT_32 * hDbl 
End Function 

Private Sub Class_Initialize() 
    Dim PerfFrequency As UINT64 
    QueryPerformanceFrequency PerfFrequency 
    pFrequency = U64Dbl(PerfFrequency) 
End Sub 

Public Property Get Elapsed() As Double 
    If pRunning Then 
     Dim pNow As UINT64 
     QueryPerformanceCounter pNow 
     Elapsed = pElapsed + (U64Dbl(pNow) - U64Dbl(pStartTS))/pFrequency 
    Else 
     Elapsed = pElapsed 
    End If 
End Property 

Public Sub Start() 
    If Not pRunning Then 
     QueryPerformanceCounter pStartTS 
     pRunning = True 
    End If 
End Sub 

Public Sub Pause() 
    If pRunning Then 
     QueryPerformanceCounter pEndTS 
     pRunning = False 
     pElapsed = pElapsed + (U64Dbl(pEndTS) - U64Dbl(pStartTS))/pFrequency 
    End If 
End Sub 

Public Sub Reset() 
    pElapsed = 0 
    pRunning = False 
End Sub 

Public Sub Restart() 
    pElapsed = 0 
    QueryPerformanceCounter pStartTS 
    pRunning = True 
End Sub 

Public Property Get Running() As Boolean 
    Running = pRunning 
End Property 

一個新的類模塊在上面的代碼粘貼並命名模塊「秒錶」。然後在你的代碼中的任何其他地方你可以做這樣的事情:

Sub DoStuff 
    Dim sw As New Stopwatch 
    sw.Start 
    myResult = SomeFunction(A, B, C) 
    sw.Pause 
    Debug.Print "SomeFunction took " & Format(sw.Elapsed * 1000, "0.000000") & " milliseconds" 
End Sub 
+1

謝謝你的答案,確實非常有用! –

+0

感謝您的回答,這可能是有用的,但我不明白,SomeFunction有什麼作用? – Synoon

+0

我應該在那裏寫我的主要功能嗎? – Synoon