Skip to content

Instantly share code, notes, and snippets.

@chase-lambert
Last active March 3, 2023 03:26
Show Gist options
  • Save chase-lambert/cb64e8a0d415c6f04b63aca3f5d02a4d to your computer and use it in GitHub Desktop.
Save chase-lambert/cb64e8a0d415c6f04b63aca3f5d02a4d to your computer and use it in GitHub Desktop.
random nerd snipe messing around
(ns area
(:require
[clojure.math :as math]
[criterium.core :as crit]))
(defmulti area :shape)
(defmethod area :square [{:keys [side]}]
(* side side))
(defmethod area :rectangle [{:keys [width height]}]
(* width height))
(defmethod area :triangle [{:keys [base height]}]
(* 0.5 base height))
(defmethod area :circle [{:keys [radius]}]
(* math/PI radius radius))
(defn make-random-shape []
(let [shapes [:square :rectangle :circle :triangle]
shape (rand-nth shapes)
lengths (case shape
:square {:side (rand-int 10)}
:rectangle {:width (rand-int 10)
:height (rand-int 10)}
:triangle {:base (rand-int 10)
:height (rand-int 10)}
:circle {:radius (rand-int 10)})]
(merge {:shape shape} lengths)))
(defn total-area [shapes]
(transduce (map area) + shapes))
(def lots-of-shapes (doall (repeatedly 400000 #(make-random-shape))))
(crit/bench (total-area lots-of-shapes)) ;; 56 ms which is 56,000 microseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment