How to achieve Asynchrony instead of Parallelism in F#

后端 未结 5 1838
无人共我
无人共我 2021-02-08 23:24

(Sticking to a common example with async fetch of many web pages)

How would I spin off multiple (hundreds) of web page requests asynchronously, and then wait for all req

5条回答
  •  情话喂你
    2021-02-08 23:51

    Here's some code that avoids the unknowns, such as web access latency. I am getting under 5% CPU utilization, and about 60-80% efficiency for both sync and async code paths.

    open System.Diagnostics
    
    let numWorkers = 200
    let asyncDelay = 50
    
    let main =
       let codeBlocks = [for i in 1..numWorkers -> 
                            async { do! Async.Sleep asyncDelay } ]
    
       while true do
          printfn "Concurrent started..."
          let sw = new Stopwatch()
          sw.Start()
          codeBlocks |> Async.Parallel |> Async.RunSynchronously |> ignore
          sw.Stop()
          printfn "Concurrent in %d millisec" sw.ElapsedMilliseconds
          printfn "efficiency: %d%%" (int64 (asyncDelay * 100) / sw.ElapsedMilliseconds)
    
          printfn "Synchronous started..."
          let sw = new Stopwatch()
          sw.Start()
          for codeBlock in codeBlocks do codeBlock |> Async.RunSynchronously |> ignore
          sw.Stop()
          printfn "Synchronous in %d millisec" sw.ElapsedMilliseconds
          printfn "efficiency: %d%%" (int64 (asyncDelay * numWorkers * 100) / sw.ElapsedMilliseconds)
    
    main
    

提交回复
热议问题