]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/utils.clj
added approx-equal function
[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 (defmacro microbench
46   " Evaluates the expression n number of times, returning the average
47     time spent in computation, removing highest and lowest values.
48
49     If the body of expr returns nil, only the timing is returned otherwise
50     the result is printed - does not affect timing.
51
52     Before timings begin, a warmup is performed lasting either 1 minute or
53     1 full computational cycle, depending on which comes first."
54   [n expr] {:pre [(> n 2)]}
55   `(let [warm-up#  (let [start# (System/currentTimeMillis)]
56                      (println "Warming up!")
57                      (while (< (System/currentTimeMillis) (+ start# (* 60 1000)))
58                             (with-out-str ~expr)
59                             (System/gc))
60                      (println "Benchmarking..."))
61          timings#  (doall
62                     (for [pass# (range ~n)]
63                       (let [start#    (System/nanoTime)
64                             retr#     ~expr
65                             timing#   (/ (double (- (System/nanoTime) start#))
66                                          1000000.0)]
67                         (when retr# (println retr#))
68                         (System/gc)
69                         timing#)))
70          runtime#  (reduce + timings#)
71          highest#  (apply max timings#)
72          lowest#   (apply min timings#)]
73      (println "Total runtime: " runtime#)
74      (println "Highest time : " highest#)
75      (println "Lowest time  : " lowest#)
76      (println "Average      : " (/ (- runtime# (+ highest# lowest#))
77                                    (- (count timings#) 2)))
78      timings#))