Skip to content

Instantly share code, notes, and snippets.

@yodiz
Created May 23, 2024 13:09
Show Gist options
  • Save yodiz/68a4b75edd5376f0e076b8e73259dbc1 to your computer and use it in GitHub Desktop.
Save yodiz/68a4b75edd5376f0e076b8e73259dbc1 to your computer and use it in GitHub Desktop.
module Program
open System.Threading
let delayInMs = 1000
let doAsync nSlow =
[ for i = 0 to nSlow - 1 do yield Async.Sleep delayInMs ]
|> Async.Parallel
|> Async.RunSynchronously |> ignore<unit array>
let runInThreadPool (fn) =
let resetEvent = new ManualResetEvent(false);
let w = System.Threading.WaitCallback(fun _ -> fn (); resetEvent.Set() |> ignore<bool>)
System.Threading.ThreadPool.QueueUserWorkItem(w) |> ignore<bool>
resetEvent
let doSync nSlow =
[
for i = 0 to nSlow - 1 do
runInThreadPool (fun () -> System.Threading.Thread.Sleep delayInMs)
]
|> List.iter (fun x -> x.WaitOne() |> ignore<bool>)
let time str fn =
let sw = System.Diagnostics.Stopwatch.StartNew()
fn ()
printfn $"'%s{str}' took %i{sw.ElapsedMilliseconds}ms"
[<EntryPoint>]
let main args =
System.Threading.ThreadPool.SetMaxThreads(System.Environment.ProcessorCount, System.Environment.ProcessorCount) |> printfn "Threads: %b"
let slowToSpin = System.Environment.ProcessorCount + 1
time "Async" (fun () -> doAsync slowToSpin)
time "Threads" (fun () -> doSync slowToSpin)
0
@yodiz
Copy link
Author

yodiz commented May 23, 2024

Threads: true
'Async' took 1027ms
'Threads' took 2016ms

C:\Users\se-mikkjel-01\source\repos\ConsoleApp7\ConsoleApp7\bin\Debug\net8.0\ConsoleApp7.exe (process 82760) exited with code 0.
Press any key to close this window . . .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment