|
1 | 1 | (ns sieve
|
2 | 2 | "Clojure implementations of The Sieve of Eratosthenes by Peter Strömberg (a.k.a. PEZ)"
|
3 |
| - (:require [criterium.core :refer [bench quick-bench with-progress-reporting]]) |
4 |
| - (:import [java.time Instant Duration])) |
| 3 | + (:require [clojure.edn]) |
| 4 | + (:import [java.time Instant Duration]) |
| 5 | + (:gen-class)) |
5 | 6 |
|
6 | 7 | ;; Disable overflow checks on mathematical ops and warn when compiler is unable
|
7 | 8 | ;; to optimise correctly.
|
|
58 | 59 | (loot (sieve 1))
|
59 | 60 | (loot (sieve 10))
|
60 | 61 | (loot (sieve 100))
|
61 |
| - (time (count (loot (sieve 1000000)))) |
| 62 | + (time (count (loot (sieve 1000000))))' |
| 63 | + (require '[criterium.core :refer [bench quick-bench with-progress-reporting]]) |
62 | 64 | (with-progress-reporting (quick-bench (sieve 1000000))))
|
63 | 65 |
|
64 | 66 | (set! *unchecked-math* true)
|
|
96 | 98 | (count (loot (sieve-ba 1000)))
|
97 | 99 | (count (loot (sieve-ba 1000000)))
|
98 | 100 | (with-progress-reporting (quick-bench (sieve-ba 1000000)))
|
99 |
| - (with-progress-reporting (bench (sieve-ba 1000000))) |
100 | 101 | (time (do (sieve-ba 1000000) nil)))
|
101 | 102 |
|
102 | 103 | (defn sieve-bs
|
|
105 | 106 | [^long n]
|
106 | 107 | (if (< n 2)
|
107 | 108 | (java.util.BitSet. 0)
|
108 |
| - (let [half-n (int (bit-shift-right n 1)) |
109 |
| - primes (doto (java.util.BitSet. n) (.set 0 half-n)) |
110 |
| - sqrt-n (long (Math/ceil (Math/sqrt (double n))))] |
| 109 | + (let [sqrt-n (unchecked-long (Math/ceil (Math/sqrt (double n)))) |
| 110 | + half-n (unchecked-int (bit-shift-right n 1)) |
| 111 | + primes (doto (java.util.BitSet. half-n) (.set (unchecked-int 0) half-n))] |
111 | 112 | (loop [p 3]
|
112 | 113 | (when (< p sqrt-n)
|
113 |
| - (when (.get primes (unchecked-int (bit-shift-right p (unchecked-int 1)))) |
114 |
| - (loop [i (bit-shift-right (unchecked-multiply p p) 1)] |
| 114 | + (when (.get primes (unchecked-int (bit-shift-right p 1))) |
| 115 | + (loop [i (bit-shift-right (* p p) 1)] |
115 | 116 | (when (< i half-n)
|
116 | 117 | (.clear primes (unchecked-int i))
|
117 |
| - (recur (unchecked-add-int i p))))) |
118 |
| - (recur (unchecked-add-int p 2)))) |
| 118 | + (recur (+ i p))))) |
| 119 | + (recur (+ p 2)))) |
119 | 120 | primes)))
|
120 | 121 |
|
121 | 122 | (defn sieve-bs-shroedinger
|
|
543 | 544 | (format-results (merge conf (benchmark sieve) {:variant variant})))
|
544 | 545 | (println (format-results (merge conf (benchmark sieve) {:variant variant})))))
|
545 | 546 |
|
| 547 | +(defn -main [& args] |
| 548 | + (run (clojure.edn/read-string (first args)))) |
| 549 | + |
546 | 550 | (comment
|
547 | 551 | (run {:warm-up? true})
|
548 | 552 | (run {:warm-up? false})
|
|
0 commit comments