scheme递归和迭代的效率测试

测试环境 Petite Chez Scheme Version 8.4 Copyright (c) 1985-2011 Cadence Research Systems

递归版本

(define fib-0 (lambda (x)
	(cond ((= x 0) 0)
		((= x 1) 1)
		(else (+ (fib-0 (- x 2)) (fib-0 (- x 1)))))))

迭代版本

(define fib-1 (lambda (n)
	(let ((i 1) (v0 1) (v1 0))
		(define func (lambda ()
			(let ((t 0))
				(cond ((= n 0) 0)
					((= n 1) 1)
					(else
						(if (< i n)
							(begin
								(set! t (+ v1 v0))
								(set! v1 v0)
								(set! v0 t)
								(set! i (+ i 1))
								(func))
							v0))))))
		(func))))
测试一下效率,结果还是有点吃惊的

> (time (fib-0 38)) 递归版本只测试到38,时间已经很长了
(time (fib-0 38))
    no collections
    5157 ms elapsed cpu time
    5149 ms elapsed real time
    0 bytes allocated
39088169
> (time (fib-1 38)) 测试下迭代版本的38,太快了,不知道时间
(time (fib-1 38))
    no collections
    0 ms elapsed cpu time
    0 ms elapsed real time
    416 bytes allocated
39088169

> (time (fib-1 38000))

(time (fib-1 38000))
    8 collections
    78 ms elapsed cpu time, including 15 ms collecting
    73 ms elapsed real time, including 29 ms collecting
    66908400 bytes allocated, including 67848240 bytes reclaimed

结果太大了,不贴在这里了。抛开分配的字节数,只看时间,迭代版本和递归版本有万倍级别的差别。

再看一个例子:n<3 f(n)=n n>=3 f(n)=f(n-1)+2f(n-2)+3f(n-3)

递归版本

(define f0 (lambda (n)
	(cond ((< n 3) n)
		(else
			(+ (f0 (- n 1)) (* 2 (f0 (- n 2))) (* 3 (f0 (- n 3))))))))
迭代版本

(define f1 (lambda (n)
	(let ((i 2)(v0 2)(v1 1)(v2 0))
		(define func (lambda ()
			(let ((t 0))
				(cond ((< n 3) n)
					(else
						(if (< i n)
							(begin
								(set! t (+ v0 (* 2 v1) (* 3 v2)))
								(set! v2 v1)
								(set! v1 v0)
								(set! v0 t)
								(set! i (+ i 1))
								(func))
							v0))))))
		(func))))
> (time (f0 33)) 时间比较长了
(time (f0 33))
    224 collections
    14828 ms elapsed cpu time, including 15 ms collecting
    14863 ms elapsed real time, including 21 ms collecting
    1886422784 bytes allocated, including 1886521072 bytes reclaimed
821337484081
> (time (f1 33)) 迭代太快,看不出时间消耗,并且资源占用也很少
(time (f1 33))
    no collections
    0 ms elapsed cpu time
    0 ms elapsed real time
    4496 bytes allocated
821337484081
> (time (f1 33000)) 扩大1000倍再看
(time (f1 33000))
    40 collections
    235 ms elapsed cpu time, including 16 ms collecting
    238 ms elapsed real time, including 5 ms collecting
    345982400 bytes allocated, including 344358960 bytes reclaimed

差不多也是万倍级别的差异。

你可能感兴趣的:(scheme,sicp,scheme)