QueryPerformanceCounter (kernel32)
Last changed: -178.94.101.155

.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

VB.NET Signature:

<DllImport("kernel32.dll", SetLastError:=True)> _
Shared Function QueryPerformanceCounter(ByRef lpPerformanceCount As Long) As Boolean
End Function

User-Defined Types:

None.

Notes:

None.

Tips & Tricks:

For this particular method, execution time is often critical. Security can be traded for additional speed by applying the SuppressUnmanagedCodeSecurity attribute to the method declaration. This will prevent the runtime from doing a security stack walk at runtime.

[DllImport("kernel32.dll"),SuppressUnmanagedCodeSecurity]
static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

Sample Code:

Imports System.Runtime.InteropServices
Imports System.Security

Friend Enum TimeState
    Started
    Stopped

End Enum

Public Class HighResTimer

    <DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity()> _
    Private Shared Function QueryPerformanceCounter(ByRef lpPerformanceCount As Long) As Boolean
    End Function

    <DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity()> _
    Private Shared Function QueryPerformanceFrequency(ByRef lpPerformanceFreq As Long) As Boolean
    End Function

    Private Shared freq As Long
    Shared Sub New()
    If Not QueryPerformanceFrequency(freq) Then
        Throw New System.ComponentModel.Win32Exception
    End If
    End Sub

    Private startTime, endTime As Long
    Private _duration As Double
    Private state As TimeState = TimeState.Stopped

    Public Sub Start()
    If state = TimeState.Started Then
        Throw New ApplicationException("Cant' start, already started")
    End If
    state = TimeState.Started
    QueryPerformanceCounter(startTime)
    End Sub

    Public Function [Stop]() As Double
    QueryPerformanceCounter(endTime)
    If state = TimeState.Stopped Then
        Throw New ApplicationException("Cant' start, already started")
    End If
    state = TimeState.Stopped
    _duration = ((endTime - startTime) / freq)
    Return _duration
    End Function

    Public ReadOnly Property Duration() As Double
    Get
        If state = TimeState.Started Then
        Throw New ApplicationException("Must call Stop() first")
        End If
        Return _duration
    End Get
    End Property

End Class

Alternative Managed API:

Documentation