Skip to content

Instantly share code, notes, and snippets.

@samth

samth/bench.rkt

Created Oct 21, 2013
Embed
What would you like to do?
Test allocation vs mutation
#lang racket
(require racket/unsafe/ops racket/performance-hint)
(define (loop0 n)
(for/sum ([i (in-range n)])
(define i+1 (unsafe-fx+ 1 i))
(define g (+ i i+1))
(define l (- i i+1))
(+ g l)))
(begin-encourage-inline
(define (f1 x y)
(cons (+ x y) (- x y)))
(define (g1 x)
(+ (unsafe-car x) (unsafe-cdr x))))
(define (loop1 n)
(for/sum ([i (in-range n)])
(g1 (f1 i (unsafe-fx+ 1 i)))))
(begin-encourage-inline
(define (f2 x y)
(values (+ x y) (- x y)))
(define (g2 a b) (+ a b)))
(define (loop2 n)
(for/sum ([i (in-range n)])
(call-with-values (lambda () (f2 i (unsafe-fx+ 1 i))) g2)))
(begin-encourage-inline
(define (f3 p x y)
(unsafe-set-mcar! p (+ x y))
(unsafe-set-mcdr! p (- x y))
p)
(define (g3 p) (+ (unsafe-mcar p) (unsafe-mcdr p))))
(define (loop3 n)
(define p (mcons #f #f))
(for/sum ([i (in-range n)])
(g3 (f3 p i (unsafe-fx+ 1 i)))))
(define K 10000000)
(collect-garbage) (collect-garbage)
'direct
(time (void (loop0 K)))
(collect-garbage) (collect-garbage)
'cons
(time (void (loop1 K)))
(collect-garbage) (collect-garbage)
'values
(time (void (loop2 K)))
(collect-garbage) (collect-garbage)
'mcons
(time (void (loop3 K)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment