Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
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 dacr/840a2784e9b32ecc7800645203bb7597 to your computer and use it in GitHub Desktop.
Save dacr/840a2784e9b32ecc7800645203bb7597 to your computer and use it in GitHub Desktop.
ZIO learning - fiber based concurrency model - using foreachPar / published by https://github.com/dacr/code-examples-manager #d90e5330-8295-498e-a2d4-621eb68bf785/8fa5a8df8cfdac03064bec5e97c08289601a5129
// summary : ZIO learning - fiber based concurrency model - using foreachPar
// keywords : scala, zio, learning, pure-functional, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : d90e5330-8295-498e-a2d4-621eb68bf785
// created-on : 2021-03-27T17:52:36+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio:2.0.13"
// ---------------------
import zio.*
import java.util.concurrent.TimeUnit
import scala.annotation.tailrec
object ThatApp extends ZIOAppDefault {
@tailrec
def factR(x: Int, accu: BigInt = 1): BigInt =
if (x == 1) accu else factR(x - 1, accu * x)
def fact(x: Int): Task[BigInt] = ZIO.attempt(factR(x))
// using parallel helpers
val computeRange = (10000 to 10500).toList
val run = for {
d0 <- Clock.currentTime(TimeUnit.MILLISECONDS)
_ <- Console.printLine(s"started")
r1 <- ZIO.foreach(computeRange)(x => fact(x))
d1 <- Clock.currentTime(TimeUnit.MILLISECONDS)
_ <- Console.printLine(s"computed sequentially factorials count = ${r1.size} in ${d1-d0}ms")
r2 <- ZIO.foreachExec(computeRange)(ExecutionStrategy.ParallelN(2))(x => fact(x))
d2 <- Clock.currentTime(TimeUnit.MILLISECONDS)
_ <- Console.printLine(s"computed parallel(2) factorials count = ${r2.size} in ${d2-d1}ms")
r3 <- ZIO.foreachPar(computeRange)(x => fact(x))
d3 <- Clock.currentTime(TimeUnit.MILLISECONDS)
_ <- Console.printLine(s"computed parallel(available cores) factorials count = ${r3.size} in ${d3-d2}ms")
} yield ()
}
ThatApp.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment