Skip to content

Instantly share code, notes, and snippets.

@mrroman
Last active February 21, 2018 11:11
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 mrroman/f2ee14e599e5afd1aba4e7c38040d10d to your computer and use it in GitHub Desktop.
Save mrroman/f2ee14e599e5afd1aba4e7c38040d10d to your computer and use it in GitHub Desktop.
A parallel sum of numbers from a core.async channel.
(ns test1.numbers
(:require [clojure.core.async :as a]))
(defn number-generator [n]
(let [c (a/chan 1024)]
(a/go
(dotimes [x n]
(a/>! c x))
(a/close! c))
c))
(defn sum-channel [ch]
(a/go-loop [s 0]
(if-some [x (a/<! ch)]
(recur (+ x s))
s)))
(defn parallel-sum [ch pnum]
(let [sums (for [_ (range pnum)]
(sum-channel ch))]
(a/reduce + 0 (a/merge sums))))
(time (a/<!! (sum-channel (number-generator 1000000)))) ; 409 ms
(time (a/<!! (parallel-sum (number-generator 1000000) 1))) ; 551 ms
(time (a/<!! (parallel-sum (number-generator 1000000) 4))) ; 1244 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment