I was looking to time some Reporting Service functionality and needed to get down to the millisecond. The DateDiff() function in VB.NET seemed to fit the bill, but natively only goes down to the Second. But on MSDN, there is some sample code that shows how to get the duration of items at the millisecond level.
The example they show is:
Dim startTime As Date = Now
' Run the process that is to be timed.
Dim runLength As Global.System.TimeSpan = Now.Subtract(startTime)
Dim millisecs As Integer = runLength.Milliseconds
Unfortunately this routine had me scratching my head when it showed some code that took 7 seconds to run as only 538 milliseconds. Repeated runs kept giving me low numbers, and always three digits. The problem with the example is that it shows how to get the portion of total time in milliseconds. It is meant for display of a time code like:
HH:MM:SS.mmmmmmm
It would show just the portion of milliseconds after the second. What they really meant to use was the property TotalMilliseconds. because if you have any process being timed that is longer than a second, their example simply wont work. Instead try the following:
Public Function TimeDuration(ByVal startTime As Date) As String
Dim runLength As Global.System.TimeSpan = Now.Subtract(startTime)
'You really want to use TotalMilliseconds to get the total
'time elapsed in Milliseconds
'Dim millisecs As Integer = runLength.TotalMilliseconds
'Instead, I would rather just convert to a nice TimeCode style string
Return (New TimeSpan(runLength.Ticks).ToString())
End Function