【发布时间】:2019-06-05 12:20:39
【问题描述】:
考虑以下两个定义:
(defun fun-add (a b) (+ a b))
(defmacro macro-add (a b) `(+ ,a ,b))
在我有限的理解中,“运行”函数会比宏快,因为“运行宏”还涉及代码扩展。但是,我使用 SBCL 得到以下结果:
CL-USER> (time (loop for i below 1e7
do (fun-add 15 25)))
Evaluation took:
0.180 seconds of real time
0.179491 seconds of total run time (0.179491 user, 0.000000 system)
99.44% CPU
396,303,718 processor cycles
0 bytes consed
NIL
CL-USER> (time (loop for i below 1e7
do (macro-add 15 25)))
Evaluation took:
0.034 seconds of real time
0.033719 seconds of total run time (0.033719 user, 0.000000 system)
100.00% CPU
74,441,518 processor cycles
0 bytes consed
NIL
为什么会这样?
【问题讨论】:
-
宏不是只需要展开一次吗?
-
嗯...是的,只是通过维护一个计数器来检查。宏确实只扩展了一次。有没有办法让它扩大多次?
-
有点违背宏的目的,不是吗?
-
@ScottHunter,也许吧。我想根据参数的类型来衡量使用宏来扩展代码的性能开销。 (此信息将在编译时通过另一个参数获得。)有没有办法衡量宏的性能?
-
我不明白你在测量什么;您说“使用宏的性能开销”,但与什么相比的开销?如果您想在一个参数已知的情况下打开一些调用代码,请使用例如编译器宏,或者如果你想更深入,使用
deftransform:stackoverflow.com/questions/44342104/…
标签: performance lisp common-lisp