使用SBCL 1.4.12,我正在阅读Stuart Shapiro的Common Lisp:交互式方法中的练习17.9,并将reverse
函数的计时应用于10,000个元素的列表。当我使用相同的列表计时此函数时,time
函数每次报告不同的字节数。
这是reverse
函数的代码:
(defun reverse2 (l1 l2)
"Returns a list consisting of the members of L1 in reverse order
followed by the members of L2 in original order."
(check-type l1 list)
(check-type l2 list)
(if (endp l1) l2
(reverse2 (rest l1)
(cons (first l1) l2))))
(defun reverse1 (l)
"Returns a copy of the list L1
with the order of members reversed."
(check-type l list)
(reverse2 l '()))
我在REPL中生成了以下列表:
(defvar *test-list* '())
(dotimes (x 10000)
(setf *test-list* (cons x *test-list*)))
以下是四次测试运行的结果:
CL-USER> (time (ch17:reverse1 *test-list*))
Evaluation took:
0.000 seconds of real time
0.000000 seconds of total run time (0.000000 user, 0.000000 system)
100.00% CPU
520,386 processor cycles
145,696 bytes consed
CL-USER> (time (ch17:reverse1 *test-list*))
Evaluation took:
0.000 seconds of real time
0.000000 seconds of total run time (0.000000 user, 0.000000 system)
100.00% CPU
260,640 processor cycles
178,416 bytes consed
CL-USER> (time (ch17:reverse1 *test-list*))
Evaluation took:
0.000 seconds of real time
0.000000 seconds of total run time (0.000000 user, 0.000000 system)
100.00% CPU
279,822 processor cycles
178,416 bytes consed
CL-USER> (time (ch17:reverse1 *test-list*))
Evaluation took:
0.000 seconds of real time
0.000000 seconds of total run time (0.000000 user, 0.000000 system)
100.00% CPU
264,700 processor cycles
161,504 bytes consed
第二次和第三次测试运行(相隔几分钟)显示相同的字节数,但其他两个显示不同的数字。我预计时间会有所不同,但我没想到会有多少字节变化。我看到HyperSpec说的是time
函数:
一般而言,这些时间并不能保证足够可靠以进行营销比较。它们的价值主要是启发式的,用于调整目的。
但我希望这适用于时间,而不是字节数。 time
报告的字节consed值是否不可靠?幕后是否有优化负责?我错过了什么?
consing的数量(在“分配的内存字节数”中)取决于所有内容:
一般来说,如果你有一个非常简单的单线程实现,它有一个非常简单的分配器和一个非常简单的GC,那么跟踪分配很容易,你将获得可靠的数字。许多Lisp实现曾经是这样的:它们很容易理解,而且你在做任何事情时都要喝很多茶(好吧,机器比较慢,但即使按照时间标准,它们仍然经常令人印象深刻)。现在Lisps有多个线程,复杂的分配器和GC,它们真的很快,但是分配的数量已经成为一个很难回答的问题,而且往往有些不可预测。