Skip to content

Instantly share code, notes, and snippets.

@hellerve
Created October 24, 2017 16:32
Show Gist options
  • Save hellerve/269a9ace0af362ab405c2b931539cc22 to your computer and use it in GitHub Desktop.
Save hellerve/269a9ace0af362ab405c2b931539cc22 to your computer and use it in GitHub Desktop.
Simple benchmarking in carp
(system-include "../bench.h")
(register get-time-elapsed (Fn [] Double))
(defn min [a]
(let [m (Double.copy (Array.nth a 0))]
(do
(for [i 1 (Array.count a)]
(let [el (Double.copy (Array.nth a i))]
(if (Double.< el m)
(set! &m el)
())))
m)))
(defn max [a]
(let [m (Double.copy (Array.nth a 0))]
(do
(for [i 1 (Array.count a)]
(let [el (Double.copy (Array.nth a i))]
(if (Double.> el m)
(set! &m el)
())))
m)))
(defn add- [a b]
(Double.+ (Double.copy a) (Double.copy b)))
(defn sum [a]
(Array.reduce add- 0.0 a))
(defn pp [a mean]
(let [sum 0.0]
(do
(for [i 0 (Array.count a)]
(let [tmp (Double.- (Double.copy (Array.nth a i)) mean)]
(set! &sum (Double.* tmp tmp))))
sum)))
(defn xx [a mean]
(let [sum 0.0]
(do
(for [i 0 (Array.count a)]
(set! &sum (Double.- (Double.copy (Array.nth a i)) mean)))
sum)))
(defn ss [a mean]
(let [tmp (xx a mean)]
(Double.- (pp a mean)
(Double./ (Double.* tmp tmp)
(Double.from-int (Array.count a))))))
(defn variance [a mean]
(Double./ (ss a mean) (Double.from-int (Array.count a))))
(defn stdev [a]
(let [mean (Double./ (sum a) (Double.from-int (Array.count a)))]
(Double.sqrt (variance a mean))))
(defmacro bench [n form]
(list 'let ['before (get-time-elapsed)
'times []]
(list 'do
(list 'for ['i 0 n]
(list 'let ['before-once (get-time-elapsed)]
(list 'do
form
(list 'set! &times (Array.push-back (Array.copy &times) (Double.- (get-time-elapsed) before-once))))))
(list 'let ['total (Double.- (get-time-elapsed) before)
'per (list 'Double./ 'total (list 'Double.from-int n))]
(do
(IO.print "Total time elapsed: ")
(IO.print &(Double.str total))
(IO.println "μs")
(IO.print "Time elapsed per run (average): ")
(IO.print &(Double.str per))
(IO.println "μs")
(IO.print "Best case: ")
(IO.print &(Double.str (min &times)))
(IO.println "μs")
(IO.print "Worst case: ")
(IO.print &(Double.str (max &times)))
(IO.println "μs")
(IO.print "Standard deviation: ")
(IO.print &(Double.str (stdev &times)))
(IO.println "μs"))))))
(defn main []
(bench 100 (IO.println "hi buddy")))
#include <sys/time.h>
double get_MINUS_time_MINUS_elapsed() {
struct timeval tv;
gettimeofday(&tv, NULL);
return 1000000 * tv.tv_sec + tv.tv_usec;;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment