Is there anyway to measure the time it takes for a block of code to be executed?
Just want to measure if my optimisations are really optimising.
Printable View
Is there anyway to measure the time it takes for a block of code to be executed?
Just want to measure if my optimisations are really optimising.
yes
you can use a timer object to accomplish what you want...
do a search in the forum for timer and you will get dearth of posts ;)
I attempted to use a timer by setting the interval to "1" then inside the timer having it increase a variable bTime by 1.
At the start of the block I'd enable the timer then disable it at the end and bTime hadn't increased at all.
So I assumed this meant that the timer didn't run its interval if a block of code is half way through being executed - or does this just mean the code is executed so quickly that 1/1000th of a second hasn't passed?
1) Set the interval to 1000
2) What are you trying to do?
3) How are you measuring the time taken for the sub to be complete?
Also there is one more way of doing it without using timers for example
Code:Sub TestTime()
Dim StartTime, EndTime
Dim Count
StartTime = Now
'#######SAMPLE CODE##########
Count = 0
For i = 1 To 1000
For j = 1 To 100000
Count = Count + 1
Next j
Next
'############################
EndTime = Now
MsgBox "Start Time: " & Format(StartTime, "hh:mm:ss") & ", End Time: " & _
Format(EndTime, "hh:mm:ss")
End Sub
You can also use a profiling tool. VB Watch is free to run on projects of <= 10 source files.
A modification of Koolsid's code:
Code:Private Sub Command1_Click()
Dim StartTime As Double
StartTime = Now
'#######SAMPLE CODE##########
For i = 1 To 2000
For j = 1 To 100000
Next
Next
'############################
MsgBox "Elapsed Time: " & Format(Now - StartTime, "hh:mm:ss")
' Accurate to the nearest second
End Sub
Code Doc: Cheers :thumb:
Thanks, Koolsid. I actually use this in all my tutorial software when tracking the elapsed time that a user takes to complete a Q&A tutorial. These can sometimes go on for hours or could be as short as a few minutes. The accuracy to the nearest second is usually sufficient.Quote:
Originally Posted by koolsid
I also run a timer in the background to show a countdown of time remaining from an allotted time, which is a bit tricky. Regardless, I always capture the start time when the form loads and record (or add to) the elapsed time when the form unloads. I then store that value as a single on a random access file.