]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/utils.clj
Solutions to 4.27, 4.28 and 4.29.
[sicp.git] / src / sicp / utils.clj
1 (ns sicp.utils)
2
3 (defn square [x] (* x x))
4
5 (defn abs
6   "find absolute value of x"
7   [x]
8   (if (< x 0) (- x) x))
9
10 (defn cube [x]
11   (* x x x))
12
13 (defn twice [x]
14   (* 2 x))
15
16 (defn half [x]
17   (/ x 2))
18
19 (defn divides? [a b]
20   (= (rem b a) 0))
21
22 (defn- find-divisor [n test-divisor]
23   (cond (> (square test-divisor)  n) n
24         (divides? test-divisor n) test-divisor
25         :else (find-divisor n (inc test-divisor))))
26
27 (defn- smallest-divisor [n]
28   (find-divisor n 2))
29
30 (defn prime? [n]
31   (= (smallest-divisor n) n))
32
33 (defn gcd [a b]
34   (if (= b 0)
35     a
36     (gcd b (rem a b))))
37
38 (defn average [ & coll]
39   (/ (reduce + coll)
40      (float (count coll))))
41
42 (defn approx-equal [x y]
43   (< (abs (- x y)) 0.00001))
44
45 (defn error [^String string]
46   (throw (Exception. string)))
47
48 (defmacro microbench
49   " Evaluates the expression n number of times, returning the average
50     time spent in computation, removing highest and lowest values.
51
52     If the body of expr returns nil, only the timing is returned otherwise
53     the result is printed - does not affect timing.
54
55     Before timings begin, a warmup is performed lasting either 1 minute or
56     1 full computational cycle, depending on which comes first."
57   [n expr] {:pre [(> n 2)]}
58   `(let [warm-up#  (let [start# (System/currentTimeMillis)]
59                      (println "Warming up!")
60                      (while (< (System/currentTimeMillis) (+ start# (* 60 1000)))
61                             (with-out-str ~expr)
62                             (System/gc))
63                      (println "Benchmarking..."))
64          timings#  (doall
65                     (for [pass# (range ~n)]
66                       (let [start#    (System/nanoTime)
67                             retr#     ~expr
68                             timing#   (/ (double (- (System/nanoTime) start#))
69                                          1000000.0)]
70                         (when retr# (println retr#))
71                         (System/gc)
72                         timing#)))
73          runtime#  (reduce + timings#)
74          highest#  (apply max timings#)
75          lowest#   (apply min timings#)]
76      (println "Total runtime: " runtime#)
77      (println "Highest time : " highest#)
78      (println "Lowest time  : " lowest#)
79      (println "Average      : " (/ (- runtime# (+ highest# lowest#))
80                                    (- (count timings#) 2)))
81      timings#))