1. 程式人生 > >《Chez Scheme初探》定義變數、遞迴、測試效能、並列程式碼編寫

《Chez Scheme初探》定義變數、遞迴、測試效能、並列程式碼編寫

普通fib函式

(define (fact n) (if (= n 1) 1
                             (* n (fact (- n 1))  )
                 )
)

尾遞迴fib函式

(define (fact-tail n) (fact-rec n n))
(define (fact-rec n p) (if (= n 1) p
                                   (let ( (m (- n 1)) ) 
                                        (fact-rec m (* p m))
                                   )
                       )
)

效能測試

(let ([a 120000]) (begin (time (begin (fact a) (+ 30 3) )) (time (begin (fact-tail a) (+ 30 3) ))))

測試結果:

(time (begin (fact a) ...))
    115 collections
    11.843750000s elapsed cpu time, including 0.031250000s collecting
    11.867882300s elapsed real time, including 0.040223800s collecting
    13241981264 bytes allocated, including 13012956832 bytes reclaimed
(time (begin (fact-tail a) ...))
    229 collections
    9.796875000s elapsed cpu time, including 0.062500000s collecting
    9.816385400s elapsed real time, including 0.084685200s collecting
    14538387792 bytes allocated, including 14538258416 bytes reclaimed
33

機器:

CPU:i7-8550U  記憶體24GB