Skip to content

Instantly share code, notes, and snippets.

@chenharryhua
Created December 3, 2024 06:53
Show Gist options
  • Select an option

  • Save chenharryhua/17ec880ca4ea56d446f89f198bb0d3fb to your computer and use it in GitHub Desktop.

Select an option

Save chenharryhua/17ec880ca4ea56d446f89f198bb0d3fb to your computer and use it in GitHub Desktop.
fs2 Stream parallel evaluation
val zoneId = ZoneId.systemDefault()
def timing(i: Int): IO[Unit] =
IO.realTimeInstant.flatMap { start =>
IO.sleep(i.seconds) >> IO.realTimeInstant.flatMap { end =>
IO.println(s"$i ${start.atZone(zoneId).toLocalTime} ${end.atZone(zoneId).toLocalTime}")
}
}
def run: IO[Unit] =
Stream
.range(9, 0, -1)
.covary[IO]
.parEvalMap(2)(i => timing(i).as(i))
.evalTap(IO.println)
.compile
.drain
.timed
.flatMap(x => IO.println(x._1.toSeconds))
@chenharryhua
Copy link
Author

parEvalMap(2)
8 17:50:09.678814 17:50:17.686298
9 17:50:09.678814 17:50:18.683858
9
8
6 17:50:18.692719 17:50:24.698327
7 17:50:18.691836 17:50:25.696038
7
6
4 17:50:25.708551 17:50:29.711102
5 17:50:25.697687 17:50:30.701130
5
4
2 17:50:30.704563 17:50:32.705055
3 17:50:30.702638 17:50:33.703962
3
2
1 17:50:33.706064 17:50:34.711416
1
25

@chenharryhua
Copy link
Author

parEvalMapUnordered

8 17:54:21.132171 17:54:29.137961
8
9 17:54:21.131990 17:54:30.137306
9
6 17:54:30.138472 17:54:36.142889
6
7 17:54:29.154331 17:54:36.155803
7
4 17:54:36.157594 17:54:40.159752
4
5 17:54:36.144740 17:54:41.145886
5
2 17:54:41.146807 17:54:43.148102
2
3 17:54:40.161769 17:54:43.162497
3
1 17:54:43.149434 17:54:44.154898
1
23

@chenharryhua
Copy link
Author

parEvalMapUnorderedUnbounded

1 17:55:18.983682 17:55:19.986228
1
2 17:55:18.983275 17:55:20.984264
2
3 17:55:18.982849 17:55:21.988747
3
4 17:55:18.982343 17:55:22.987737
4
5 17:55:18.981703 17:55:23.983625
5
6 17:55:18.981079 17:55:24.985232
6
7 17:55:18.979924 17:55:25.984090
7
8 17:55:18.979299 17:55:26.983676
8
9 17:55:18.979298 17:55:27.981441
9
9

@chenharryhua
Copy link
Author

parEvalMapUnbounded

1 17:58:30.013380 17:58:31.017545
2 17:58:30.012814 17:58:32.013894
3 17:58:30.012217 17:58:33.016962
4 17:58:30.011605 17:58:34.014852
5 17:58:30.010772 17:58:35.012524
6 17:58:30.010190 17:58:36.013038
7 17:58:30.009157 17:58:37.012330
8 17:58:30.007541 17:58:38.015076
9 17:58:30.007534 17:58:39.012701
9
8
7
6
5
4
3
2
1
9

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