Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@manofstick
Created October 25, 2016 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manofstick/b685a5acfe99f39f44c9cf06b89d2fe2 to your computer and use it in GitHub Desktop.
Save manofstick/b685a5acfe99f39f44c9cf06b89d2fe2 to your computer and use it in GitHub Desktop.
Seq Performance Various Sources
open System.Diagnostics
let createSources size f = [
"array", (lazy (Array.init size f :> seq<_>))
"list", (lazy (List.init size f :> seq<_>))
"computation expression", (lazy (seq {
let mutable x = 0
while x < size do
yield f x
x <- x + 1 }))
"unfold", (lazy (0
|> Seq.unfold (fun n ->
if n < size
then Some (f n, n+1)
else None)))
"infinite", (lazy (Seq.initInfinite f |> Seq.take size))
"append", (lazy (let dataA = Array.init (size/2) f
let dataB = Array.init (size-(size/2)) (fun x -> f (x + (size/2)))
Seq.append dataA dataB))
"many append", (lazy (let mutable data = [|f 0|] :> seq<_>
for i = 1 to size-1 do
data <- Seq.append data [|f i|]
data))
"concat", (lazy (let dataA = Array.init (size/2) f
let dataB = Array.init (size-(size/2)) (fun x -> f (x + (size/2)))
Seq.concat [dataA; dataB]))
"many concat", (lazy (Seq.concat (Array.init size (fun x -> [|f x|]))))
]
let timeRun maxTotalMs count name (lazyData:Lazy<_>) f checksum =
let data = lazyData.Force ()
let doRun () =
let sw = Stopwatch.StartNew ()
let maxTime = maxTotalMs/count
data |> f sw (int64 maxTime)
let warmUp = doRun ()
let sw = Stopwatch.StartNew ()
let mutable i = 0
let mutable failed = false
while i < count do
let total = doRun ()
if total <> checksum then
failed <- true
i <- i + 1
if failed then
printfn "%s (FAILED)" name
else
printfn "%s (%d)" name sw.ElapsedMilliseconds
let seq_mfms (sw:Stopwatch) timeout data =
data
|> Seq.takeWhile (fun _ -> sw.ElapsedMilliseconds < timeout)
|> Seq.map (fun n -> n * 5L)
|> Seq.filter (fun n -> n % 7L <> 0L)
|> Seq.map (fun n -> n / 11L)
|> Seq.sum
open System.Linq
let linq_mfms (sw:Stopwatch) timeout (data:seq<_>) =
data
.TakeWhile(fun _ -> sw.ElapsedMilliseconds < timeout)
.Select(fun n -> n * 5L)
.Where(fun n -> n % 7L <> 0L)
.Select(fun n -> n / 11L)
.Sum()
[<EntryPoint>]
let main argv =
printfn "----seq test"
let sources =
createSources 1000 int64
|> Seq.iter (fun (name, thing) -> timeRun 50000 10000 name thing seq_mfms 194351L)
printfn "----linq test"
let sources =
createSources 1000 int64
|> Seq.iter (fun (name, thing) -> timeRun 50000 10000 name thing linq_mfms 194351L)
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment