Timing a Function in F#
This can be useful for capturing how long an operation takes to execute, it also nicely demonstrates how generics operate in F#.
Modified from the original version found in the F# Programming Wikibook
open System.Diagnostics
type TimedOperation<'T> = {millisecondsTaken:int64; returnedValue:'T}
let timeOperation<'T> (func: unit -> 'T): TimedOperation<'T> =
let timer = new Stopwatch()
timer.Start()
let returnValue = func()
timer.Stop()
{millisecondsTaken=timer.ElapsedMilliseconds; returnedValue=returnValue}
I found it interesting that, when writing this example, the implicit type inference was smart enough to work out the signature of the func
parameter for me.
I've been explicit above however I could have wrote the function signature as
let timeOperation func =
Update Below is an async version:
let timeAsyncOperation<'T> (func: unit -> Async<'T>): Async<TimedOperation<'T>> = async {
let timer = new Stopwatch()
timer.Start()
let! returnValue = func()
timer.Stop()
return {millisecondsTaken=timer.ElapsedMilliseconds; returnedValue=returnValue}
}
If anyone has had experience with using async in F#, I'd be interested to know if this is the correct way to time asynchronous operations. I worry that awaiting the response with skew the results so they don't just include the time for the operation to resolve.