Created
October 6, 2023 20:49
-
-
Save samth/c20d0421f3504158f5ddae16c6264201 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(struct time-result [elapsed gc cpu] #:prefab) | |
(define (time-function func N) | |
(let loop ((n N) (results '())) | |
(cond | |
[(zero? n) (reverse results)] ; Return the results in reverse order | |
[else | |
(let-values ([(result elapsed gc-time cpu-time) (time-apply func '())]) | |
(loop (- n 1) (cons `#s(time-result ,elapsed ,gc-time ,cpu-time) results)))]))) | |
; Example usage: Define a sample function to be timed | |
(define (sample-function) | |
(define result 0) | |
(for ([i (in-range (random 10000000))]) | |
(set! result (+ result i))) | |
result) | |
; Time the sample function and print the results | |
(define timings (time-function sample-function 50)) | |
;(for-each (λ (time) (displayln (format "Time: ~a ms" time))) timings) | |
(define (convert a1 b1 a2 b2 a) | |
(/ (+ (* b1 (- a2 a)) (* b2 (- a a1))) (- a2 a1))) | |
(define (plot-box-chart vals) | |
(define max-value (apply max vals)) | |
(define box-chars " ▁▂▃▄▅▆▇█") | |
(define double-box-chars | |
(append (for/list ([c box-chars]) (cons c #\space)) | |
(for/list ([c box-chars]) (cons #\█ c)))) | |
(define num-chars (length double-box-chars)) ; Number of box drawing characters | |
(define (scale v) | |
(floor (convert 0 0 max-value (sub1 num-chars) v)) | |
#; | |
(/ (* 2 num-chars) max-value)) ; Adjust to fit within the available box characters | |
; Scale the values to fit within the available box characters | |
(define scaled-values (map scale vals)) | |
; Display the chart in the console | |
(define-values (row1 row2) | |
(for/lists (r1 r2) ([s (in-list scaled-values)]) | |
(match-define (cons c1 c2) (list-ref double-box-chars s)) | |
(values c1 c2))) | |
(string-append (apply string row2) "\n" (apply string row1))) | |
;(displayln (plot-box-chart (map time-result-elapsed timings))) | |
(define-syntax (bench stx) | |
(syntax-case stx () | |
[(_ e n) | |
#'(begin (collect-garbage) | |
(displayln | |
(plot-box-chart | |
(map time-result-elapsed (time-function (lambda () e) n)))))] | |
[(_ e) #'(bench e 50)])) | |
(provide bench sample-function) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment