Skip to content

Instantly share code, notes, and snippets.

@rctay
Created August 16, 2010 14:18
Show Gist options
  • Save rctay/527012 to your computer and use it in GitHub Desktop.
Save rctay/527012 to your computer and use it in GitHub Desktop.
[racket] benchmark helper
;
; Runs '(proc)' over 'n' times of 'MAX_RUNS', display stats collected from
; '(time-apply)'.
;
; Sample session:
; > (define (factorial-iter n)
; (if (<= n 1)
; 1
; (foldl * 1 (build-list n add1))))
; > (benchmark 5 factorial-iter 100)
; stats for factorial-iter
; 5 runs of 1000 times
; cpu: (94 46 63 47 47)
; real: (93 47 63 47 46)
; gc: (47 0 0 0 0)
; >
;
(define (benchmark n proc . args)
(define MAX_RUNS 1000) ; number of times to run (proc)
; collect time taken for (run)
(define (get-runs)
; runs (proc) with args, MAX_RUNS times
(define (run)
(do ([i MAX_RUNS (- i 1)])
((<= i 0))
(apply proc args)))
; chain results of (time-apply)
(map (lambda (_)
(cdr ; strip out return value of (proc)
(call-with-values ; pack (time-apply) into a list
(lambda () (time-apply run '()))
list)))
(build-list n values)))
; takes ((a1 b1 c1) (a2 b2 c2)),
; returns ((a1 a2) (b1 b2) (c1 c2))
(define (invert-list p_list)
; helper function to get idx-th element from the lists in p_list
(define (get-slice pp_list idx)
(map (lambda (x) (list-ref x idx)) pp_list))
; slice each column
(map (lambda (i) (get-slice p_list i))
(build-list
; get the number of columns from the first list
(length (car p_list))
values)))
; format results nicely
(define (print-time p_list)
(printf "stats for ~a\n" (object-name proc))
(printf "~a runs of ~a times\n" n MAX_RUNS)
(printf "cpu: ~a\n" (list-ref p_list 0))
(printf "real: ~a\n" (list-ref p_list 1))
(printf "gc: ~a\n" (list-ref p_list 2)))
; do stuff!
(print-time
(invert-list
(get-runs))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment