Setf变量到计算时间?

bou*_*ekv 0 common-lisp

我想将变量设置为这样的计算时间

(setf a (time (+ 1 1)))
Run Code Online (Sandbox Code Playgroud)

但不是时间我得到这个

Break 1 [7]> a
2
Run Code Online (Sandbox Code Playgroud)

如何设置计算时间?

Lar*_*off 6

使用GET-INTERNAL-RUN-TIME(或GET-INTERNAL-REAL-TIME):

(setf a
      (let ((start (get-internal-run-time)))
        (+ 1 1) ;This is the computation you want to time.
        (- (get-internal-run-time) start)))
Run Code Online (Sandbox Code Playgroud)

如果你想在几秒钟内得到结果,除以INTERNAL-TIME-UNITS-PER-SECOND.

如果你这么做的话,你可能想要制作一个函数或宏.

  • 确保编译器没有删除计算可能很有用,因为它不会产生副作用,可以在编译时计算和/或不使用结果. (3认同)

Rai*_*wig 5

看看Lars的答案.

TIME将实现相关信息写入跟踪输出.如果您希望其输出为字符串:

(with-output-to-string (*trace-output*)
  (time (+ 1 1)))
Run Code Online (Sandbox Code Playgroud)