Skip to content

Instantly share code, notes, and snippets.

@slipset
Created March 7, 2023 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slipset/a2b885ecf207ce153e09baa6f8f4957e to your computer and use it in GitHub Desktop.
Save slipset/a2b885ecf207ce153e09baa6f8f4957e to your computer and use it in GitHub Desktop.
(ns area3
(:require
[clojure.math :as math]
[criterium.core :as crit]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* false)
(definterface IArea2
(^double area []))
;(require '[clj-java-decompiler.core :refer [decompile]])
(defrecord Square [^double side]
IArea2
(area [this]
(Math/pow side (double 2))))
(defrecord Rectangle [^double width ^double height]
IArea2
(area [_]
(* width height)))
(defrecord Triangle [^double base ^double height]
IArea2
(area [_]
(* 0.5 base height)))
(defrecord Circle [^double radius]
IArea2
(area [this]
(* math/PI (Math/pow radius (double 2)))))
(defn make-random-shape []
(let [shapes [:square :rectangle :circle :triangle]
shape (rand-nth shapes)]
(case shape
:square (->Square (rand-int 10))
:rectangle (->Rectangle (rand-int 10) (rand-int 10))
:triangle (->Triangle (rand-int 10) (rand-int 10))
:circle (->Circle (rand-int 10)))))
(defn total-area [shapes]
(loop [n (double 0)
[^IArea2 s & r] shapes]
(if s
(recur (+ n (.area s)) r)
n)))
(def lots-of-shapes (doall (repeatedly 400000 #(make-random-shape))))
(crit/quick-bench (total-area lots-of-shapes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment