Skip to content

Instantly share code, notes, and snippets.

@lulu-berlin
Created August 6, 2015 17:28
Show Gist options
  • Save lulu-berlin/e22c6eb9a46cd08f1188 to your computer and use it in GitHub Desktop.
Save lulu-berlin/e22c6eb9a46cd08f1188 to your computer and use it in GitHub Desktop.
An accurate timer for F# without using System.Diagnostics
//
// This is in fact a thin wrapper around QueryPerformanceCounter() and QueryPerformanceFrequency().
// When those are not available it falls back to System.DateTime.UtcNow.Ticks.
// This module is based on the C# code of StopWatch.
// See: http://referencesource.microsoft.com/#System/services/monitoring/system/diagnosticts/Stopwatch.cs
//
open System.Runtime.InteropServices
open System.Runtime.Versioning
[<AutoOpen>]
module private TimerInternal =
[<DllImport("kernel32.dll")>]
[<ResourceExposure(ResourceScope.None)>]
extern bool QueryPerformanceCounter (int64& value)
[<DllImport("kernel32.dll")>]
[<ResourceExposure(ResourceScope.None)>]
extern bool QueryPerformanceFrequency (int64& value)
module Timer =
let ElapsedTicks =
let mutable frequency = 0L
if QueryPerformanceFrequency &frequency
then let tickFrequency = 10000000L / frequency
fun () -> let mutable timestamp = 0L
QueryPerformanceCounter &timestamp |> ignore
timestamp * tickFrequency
else fun () -> DateTime.UtcNow.Ticks
let inline ElapsedMilliseconds () = ElapsedTicks () / 10000L
//
// ElapsedTicks () returns the number of ticks since start: 10,000 tick = 1 millisecond
// ElapsedMilliseconds () returns the number of milliseconds since start
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment