Database Reference
In-Depth Information
Getting ready
From the
Partitioning Monte Carlo simulations for better pmap performance
recipe, we'll use
the same imports, as well as the
rand-point
,
center-dist
, and
mc-pi
functions. Along
with these, we also need to
require
the reducers and Criterium libraries:
(require '[clojure.core.reducers :as r])
(use 'criterium.core)
Also, if you're using Java 1.6, you'll need the ForkJoin library, which you can get by adding
this to your
project.clj
dependencies:
[org.codehaus.jsr166-mirror/jsr166y ""1.7.0""]
How to do it…
1.
This version of the Monte Carlo pi approximation algorithm will be structured in
a similar manner to how
mc-pi
was structured in the
Partitioning Monte Carlo
simulations for better pmap performance
recipe. First, we'll deine a
count-in-
circle-r
function that uses the reducers library to compose the processing and
spread it over the available cores:
(defn count-items [c _] (inc c))
(defn count-in-circle-r [n]
(->> (repeatedly n rand-point)
vec
(r/map center-dist)
(r/filter #(<= % 1.0))
(r/fold + count-items)))
(defn mc-pi-r [n]
(* 4.0 (/ (count-in-circle-r n) n)))
2.
Now, we can use Criterium to compare the two functions:
user=> (quick-bench (mc-pi 1000000))
WARNING: Final GC required 1.5511109061811519 % of runtime
WARNING: Final GC required 1.3658615618441179 % of runtime
Evaluation count : 6 in 6 samples of 1 calls.
Execution time mean : 983.603832 ms
Execution time std-deviation : 16.553276 ms
Execution time lower quantile : 964.015999 ms ( 2.5%)
Execution time upper quantile : 1.007418 sec (97.5%)