为什么 TIME 报告的字节数对于不同的调用不同?



使用 SBCL 1.4.12,我正在查看 Stuart Shapiro 的Common Lisp: An Interactive Approach中的练习 17.9,并对应用于 10,000 个元素列表的reverse函数进行计时。当我使用相同的列表对这个函数进行计时时,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报告的字节数值是否不可靠?是否有导致此的幕后优化?我错过了什么?

consing的数量(在"分配的内存字节数"意义上)取决于一切:

  • 这取决于您分配了多少类型的对象;
  • 取决于分配器的精细实现细节,例如它是否以大块分配以及是否记录了大块分配之间的"分配";
  • 这取决于垃圾收集器 -- 一个是触发的吗?如果是的话,是什么样的?GC有多毛? GC 本身是否分配?如何在指导性案例中计算分配?
  • 这取决于系统是否正在执行其他分配,例如在其他线程中,以及该分配是否在您的线程中被计算在内 - 是否只有一个分配器或每个线程分配器?
  • 这取决于月相以及冥王星是否是行星;
  • 等等。

一般来说,如果你有一个非常简单的单线程实现,有一个非常简单的分配器和一个非常简单的GC,那么跟踪分配很容易,你会得到可靠的数字。 许多 Lisp 实现曾经是这样的:它们很容易理解,在他们做任何事情时你必须喝很多茶(好吧,那时机器更慢,但即使按照当时的标准,它们仍然经常令人印象深刻地慢)。 现在 Lisps 有多个线程、复杂的分配器和 GC,它们非常快,但是发生多少分配已经成为一个很难回答的问题,而且通常有点不可预测。

最新更新