灯下 登录
计算机科学 / SICP / 5.5.7 Interfacing Compiled Code to the Evaluator

Exercise 5.45 · 习题

Exercise 5.45: By comparing the stack operations
used by compiled code to the stack operations used by the evaluator for the
same computation, we can determine the extent to which the compiler optimizes
use of the stack, both in speed (reducing the total number of stack operations)
and in space (reducing the maximum stack depth). Comparing this optimized
stack use to the performance of a special-purpose machine for the same
computation gives some indication of the quality of the compiler.

Exercise 5.27 asked you to determine, as a function of n, the number
of pushes and the maximum stack depth needed by the evaluator to compute n
!
using the recursive factorial procedure given above. Exercise 5.14 asked
you to do the same measurements for the special-purpose factorial machine shown
in Figure 5.11. Now perform the same analysis using the compiled
factorial procedure.

Take the ratio of the number of pushes in the compiled version to the number of
pushes in the interpreted version, and do the same for the maximum stack depth.
Since the number of operations and the stack depth used to compute n
! are
linear in n, these ratios should approach constants as n becomes large.
What are these constants? Similarly, find the ratios of the stack usage in the
special-purpose machine to the usage in the interpreted version.

Compare the ratios for special-purpose versus interpreted code to the ratios
for compiled versus interpreted code. You should find that the special-purpose
machine does much better than the compiled code, since the hand-tailored
controller code should be much better than what is produced by our rudimentary
general-purpose compiler.

Can you suggest improvements to the compiler that would help it generate code

that would come closer in performance to the hand-tailored version?

练习 5.45:通过比较编译代码与求值器在同一计算中使用的栈操作,我们可以衡量编译器在栈使用方面的优化程度——既包括速度(减少栈操作总次数),也包括空间(降低最大栈深度)。将这种优化后的栈使用与专用机器在同一计算上的性能相比较,可以在一定程度上反映编译器的质量。

练习 5.27 要求你确定,作为 n 的函数,求值器用上述递归阶乘过程计算 n! 所需的压栈次数和最大栈深度。练习 5.14 要求你对图 5.11 所示的专用阶乘机器做同样的测量。现在对编译后的阶乘过程进行相同的分析。

计算编译版本与解释版本的压栈次数之比,以及最大栈深度之比。由于计算 n! 所需的操作次数和栈深度均与 n 成线性关系,当 n 趋于无穷时,这些比值应趋近于常数。这些常数是多少?类似地,求专用机器与解释版本的栈使用量之比。

将专用机器与解释代码的比值和编译代码与解释代码的比值加以比较。你应该会发现,专用机器的表现远优于编译代码,因为手工定制的控制器代码应当比我们这个初级通用编译器所生成的代码好得多。

你能提出哪些改进编译器的建议,使其生成的代码在性能上更接近手工定制的版本?