Skip to content

Instantly share code, notes, and snippets.

@yodiz
Created May 16, 2019 20:06
Show Gist options
  • Save yodiz/4f98fac89673d93fdaf2c015ed922452 to your computer and use it in GitHub Desktop.
Save yodiz/4f98fac89673d93fdaf2c015ed922452 to your computer and use it in GitHub Desktop.
Timing of fold-functions in F#
let inline fold f a (xs: _ []) =
let mutable a = a
for i=0 to xs.Length-1 do
a <- f a xs.[i]
a
let afold f a (xs: _ []) =
let mutable a = a
for i=0 to xs.Length-1 do
a <- f a xs.[i]
a
let time name n x =
let sw = System.Diagnostics.Stopwatch.StartNew()
for i = 0 to n do
x()
sw.Stop()
printfn "Executed %s %i times, took %ims " name n sw.ElapsedMilliseconds
let a = [|0..50000|]
//
time "inline fold" 1000 (fun () -> fold (fun s x -> s + x) 0 a |> ignore<int>)
time "Array.fold fold" 1000 (fun () -> Array.fold (fun s x -> s+x) 0 a |> ignore<int>)
time "fold-fn fold" 1000 (fun () -> afold (fun s x -> s+x) 0 a |> ignore<int>)
//Executed inline fold 1000 times, took 15ms
//Executed Array.fold fold 1000 times, took 70ms
//Executed fold-fn fold 1000 times, took 666ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment