Imports System
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Public Class StopWatch
<DllImport("Kernel32.dll")> _
Shared Function QueryPerformanceCounter(ByRef lpPerformanceCount As Long) As Boolean
End Function
<DllImport("Kernel32.dll")> _
Shared Function QueryPerformanceFrequency(ByRef lpFrequency As Long) As Boolean
End Function
Private start As Long
Private stops As Long
Private frequency As Long
Private Const multiplier As Decimal = 1000000000.0
Public Sub New()
If QueryPerformanceFrequency(frequency) = False Then
Throw New Win32Exception
End If
End Sub
Public Sub Starts()
QueryPerformanceCounter(start)
End Sub
Public Sub Parse()
QueryPerformanceCounter(stops)
End Sub
Public Function Duration(ByVal iterations As Integer) As Double
Return (((CType((stops - start), Double) * CType(multiplier, Double)) _
/ CType(frequency, Double)) / iterations)
End Function
End Class
Dim mTimer As New StopWatch
'Measure without boxing
mTimer.Starts()
For i = 0 To 1000000000.0
'do some work to time
Next
mTimer.Parse()
'Calculate time per iteration in nanoseconds
dim result as decimal = mTimer.Duration(i)
博客展示了一个名为StopWatch的类,通过导入系统相关命名空间,利用DllImport调用Kernel32.dll中的函数实现性能计时。该类有开始、停止计时及计算持续时间的方法,最后通过实例化该类对一段代码进行计时并计算每次迭代的时间。

被折叠的 条评论
为什么被折叠?



