Simulation is useful not only for verifying the correctness of a proposed
machine design but also for measuring the machine’s performance. For example,
we can install in our simulation program a “meter” that measures the number
of stack operations used in a computation. To do this, we modify our simulated
stack to keep track of the number of times registers are saved on the stack and
the maximum depth reached by the stack, and add a message to the stack’s
interface that prints the statistics, as shown below. We also add an operation
to the basic machine model to print the stack statistics, by initializing
the-ops in make-new-machine to
模拟不仅有助于验证所提议的机器设计的正确性,还可用于度量机器的性能。例如,我们可以在模拟程序中安装一个"计量器",测量某次计算中栈操作的使用次数。为此,我们修改模拟栈,使其跟踪寄存器被保存到栈上的次数以及栈所达到的最大深度,并在栈的接口中添加一条用于打印统计信息的消息,如下所示。我们还向基本机器模型添加了一个用于打印栈统计信息的操作,做法是在 `make-new-machine` 中将 `the-ops` 初始化为:
Here is the new version of make-stack:
以下是 `make-stack` 的新版本:
Exercise 5.15 through Exercise 5.19 describe other useful
monitoring and debugging features that can be added to the register-machine
simulator.
练习 5.15 至练习 5.19 描述了可以添加到寄存器机器模拟器中的其他有用的监控和调试功能。
(list (list 'initialize-stack
(lambda ()
(stack 'initialize)))
(list 'print-stack-statistics
(lambda ()
(stack 'print-statistics)))) (define (make-stack)
(let ((s '())
(number-pushes 0)
(max-depth 0)
(current-depth 0))
(define (push x)
(set! s (cons x s))
(set! number-pushes (+ 1 number-pushes))
(set! current-depth (+ 1 current-depth))
(set! max-depth
(max current-depth max-depth)))
(define (pop)
(if (null? s)
(error "Empty stack: POP")
(let ((top (car s)))
(set! s (cdr s))
(set! current-depth
(- current-depth 1))
top)))
(define (initialize)
(set! s '())
(set! number-pushes 0)
(set! max-depth 0)
(set! current-depth 0)
'done)
(define (print-statistics)
(newline)
(display (list 'total-pushes
'=
number-pushes
'maximum-depth
'=
max-depth)))
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize)
(initialize))
((eq? message 'print-statistics)
(print-statistics))
(else
(error "Unknown request: STACK"
message))))
dispatch))