Exercise 5.15. Add instruction counting to the register machine simulation. That is, have the machine model keep track of the number of instructions executed. Extend the machine model's interface to accept a new message that prints the value of the instruction count and resets the count to zero. ———————————————————————————————————————————————————————————————————————— Code is in 5.15.scm Using the same factorial machine to test, calculating n! seems to take 11n - 6 instructions: 1 ]=> (test 2) (instruction-count = 16) ;Value: 2 1 ]=> (test 3) (instruction-count = 27) ;Value: 6 1 ]=> (test 4) (instruction-count = 38) ;Value: 24 1 ]=> (test 5) (instruction-count = 49) ;Value: 120 1 ]=> (test 6) (instruction-count = 60) ;Value: 720 1 ]=> (test 7) (instruction-count = 71) ;Value: 5040 1 ]=> (test 8) (instruction-count = 82) ;Value: 40320 The changes made to the simulator: --- ch5-regsim.scm 2010-03-16 02:00:34.000000000 -0600 +++ 5.15.scm 2010-03-27 22:49:41.000000000 -0600 @@ -99,7 +99,8 @@ (let ((pc (make-register 'pc)) (flag (make-register 'flag)) (stack (make-stack)) - (the-instruction-sequence '())) + (the-instruction-sequence '()) + (instruction-counter 0)) (let ((the-ops (list (list 'initialize-stack (lambda () (stack 'initialize))) @@ -126,6 +127,7 @@ (if (null? insts) 'done (begin + (set! instruction-counter (+ instruction-counter 1)) ((instruction-execution-proc (car insts))) (execute))))) (define (dispatch message) @@ -140,6 +142,9 @@ (lambda (ops) (set! the-ops (append the-ops ops)))) ((eq? message 'stack) stack) ((eq? message 'operations) the-ops) + ((eq? message 'read-instruction-count) + (display (list 'instruction-count '= instruction-counter)) (newline) + (set! instruction-counter 0)) (else (error "Unknown request -- MACHINE" message)))) dispatch)))