Public Class CFPS
    <System.Runtime.InteropServices.DllImport("kernel32.dll")> _
    Private Shared Function QueryPerformanceCounter(ByRef lpPerformanceCount As Long) As Boolean
    End Function

    <System.Runtime.InteropServices.DllImport("kernel32.dll")> _
    Private Shared Function QueryPerformanceFrequency(ByRef lpFrequency As Long) As Boolean
    End Function

    Private m_bEnoughDataExist As Boolean = False
    Private m_nCurPos As Integer = 0
    Private m_nSampleCount As Integer = 0
    Private m_nFrequency As Long
    Private m_nCounterLog() As Long

    Public Sub New(ByVal nSampleCount As Integer)
        m_nSampleCount = nSampleCount
        ReDim m_nCounterLog(m_nSampleCount)
        QueryPerformanceFrequency(m_nFrequency)

    End Sub

    Public Sub Check()
        QueryPerformanceCounter(m_nCounterLog(m_nCurPos))
        m_nCurPos = m_nCurPos + 1
        If m_nSampleCount <= m_nCurPos Then
            m_bEnoughDataExist = True
            m_nCurPos = 0
        End If
    End Sub

    Public Function GetFPS() As Double
        Dim nStartPos As Integer = m_nCurPos
        Dim nEndPos As Integer = m_nCurPos - 1
        If nEndPos < 0 Then
            nEndPos = m_nSampleCount - 1
        End If
        Dim nCurSampleCount As Integer = m_nSampleCount - 1

        If Not m_bEnoughDataExist Then
            nStartPos = 0
            nEndPos = m_nCurPos - 1
            nCurSampleCount = m_nCurPos - 1
        End If

        Dim dblReval As Double = 0.0

        If 1 <= nCurSampleCount Then
            Dim nDelta As Long = m_nCounterLog(nEndPos) - m_nCounterLog(nStartPos)
            dblReval = nCurSampleCount * m_nFrequency / nDelta
        End If
        System.Diagnostics.Debug.WriteLine("CurPos=" & m_nCurPos.ToString() & "," & dblReval.ToString("0.0") & "FPS")
        Return (dblReval)
    End Function

    Public Sub Reset()
        m_bEnoughDataExist = False
        m_nCurPos = 0
    End Sub

End Class
