Last active
February 21, 2018 11:11
-
-
Save mrroman/f2ee14e599e5afd1aba4e7c38040d10d to your computer and use it in GitHub Desktop.
A parallel sum of numbers from a core.async channel.
This file contains 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
(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