Last active
May 25, 2024 10:18
-
-
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/877cd2c96e0783e18fa4c57632335f64b0ce319e
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.4.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