kyle_burton ([info]kyle_burton) wrote,
@ 2008-04-28 17:05:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
Entry tags:lisp

Compile Time Evaluation, w/o Macros

We all have constants in our applications, sometimes we have
numeric values that are only used once and are clearer if they're left
as an expression (like the number of seconds in a day, well these
things are better off as constants in many cases, though I'm only
using it as an example).



(defun days->seconds (days)
  (* days (* 24 60 60)))

(format t "seconds in ~a days:~a~&" 1 (days->seconds 1))

(time (loop repeat 1000000
	    do (days->seconds 10)))
 => 2.093 sec.


In common lisp there is a reader macro you can use to have these
kinds of expressions executed at compile time - and thus use no CPU
time during your running application (or even within the compiled
executable):



(defun compile-time-days->seconds (days)
  (* days #.(* 24 60 60)))

(time (loop repeat 1000000
	    do (compile-time-days->seconds 10)))
 => 1.87s


Admittedly in this case it's not a worthwhile improvement in
performance - but these are the kinds of things many technologies
represent as build processes. When you're configuring a build to be
specialized for a locale, or particular production environment, you
either factor those parts of the application into a configuration
file, or you generate code (almost certainly with some tool set which is
not your programming language).




(1 comment) - (Post a new comment)


[info]xach
2008-04-29 05:00 pm UTC (link)
I would be pretty surprised if your Common Lisp environment did not convert (* 24 60 60) to a constant without resorting to the #. trick. Check DISASSEMBLE output.

(Reply to this)


(1 comment) - (Post a new comment)

Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…