On Mar 12, 1:03 am, "Lou Franco" <
loumfra...@gmail.com> wrote:
> Today I tried to write a parallel prime number sieve with agentshttp://
www.loufranco.com/blog/files/20-Days-of-Clojure-Day-11.html
>
> I found some oddities.
>
> 1. my sequential prime number sieve seemed to use both of my CPU's
> 2. When I was done it ran much slower (my approach was very naive,
> admittedly)
>
> Any insights would be appreciated.
I'm sorry to say I can't think of a less promising candidate for
parallelization :(
The 3 things you would want in something to parallelize are
independent data/work, moderate-to-course-grained work units and/or
complex coordination logic that would be simplified with threads.
(Note - wanting it to run faster is not enough :)
Here you have none of those - the data/work is interdependent (more
later), the work is very fine grained (seq walk and a remainder test),
and the logic was pretty elegant.
It ends up the sieve is inherently serial, that is, the value of the
sieve is that the twosie stage drops every other value so the threesie
stage never has to process it. Precisely to the extent you parallelize
it, you increase your work. You can see that as follows:
;a counter for divisible?
(def divs (ref 0))
;redefine w/counter
(defn divisible? [x y]
(sync nil (alter divs inc))
(= (rem x y) 0))
and use this definition in primes and par-primes.
(def divs (ref 0))
(prn (take 50 (primes)))
-> (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179
181 191 193 197 199 211 223 227 229)
@divs
-> 1518
;reset
(def divs (ref 0))
(prn (take 50 (par-primes)))
-> (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179
181 191 193 197 199 211 223 227 229)
@divs
-> 5735
So you're doing more than 3x the work, with substantial per-unit
overhead.
Unfortunately this effort is destined for disappointment. You might
want to try another problem.
Rich