One rather complex procedure is cache, which creates a procedure that generates and caches a value. cache takes a function to generate the cache lifetime, as well as a function to generate the value to cache.
The value function is executed the first time the created procedure is called, and will be executed again only if the created procedure is called when the cache lifetime has expired. Otherwise, the cached value is returned. Typically a cache is used when the value function is something expensive to evaluate.
The motivation behind dynamically computing the cache lifetime is that the lifetime can be modified for an existing cache, for instance through a global variable.
arc> (= mycache (cache (fn () 10) (fn () (prn "evaluated") (tostring (system "date"))))) #<procedure> arc> (mycache) evaluated "Mon Mar 10 21:08:33 PDT 2008\n" arc> (mycache) "Mon Mar 10 21:08:33 PDT 2008\n" arc> (mycache) evaluated "Mon Mar 10 21:08:46 PDT 2008\n"
date [time]
Displays the specified date (or current date by default). This works only on Unix-like systems.
|
>(date) 2008-02-20 |
seconds
Returns current time in seconds, from a platform-specific
starting date.
|
>(seconds) 1206305331 |
msec
Returns current time in milliseconds. The time is from an
arbitrary starting date, and can wrap or be negative.
|
>(msec) -580478217 |
current-gc-milliseconds
Returns the amount of time spent in garbage
collection.
|
>(current-gc-milliseconds) 9300 |
current-process-milliseconds
Returns the number of milliseconds of
processor time used.
|
>(current-process-milliseconds) 26145 |
since t0
Displays the number of seconds since
t0. The base time t0 should come from seconds. |
>(let t0 (seconds) (sleep 1) (since t0)) 1 |
hours-since t0
Displays number of hours since
t0. |
>(let t0 (seconds) (sleep 1) (hours-since t0)) 1/60 |
days-since t0
Displays number of days since
t0. |
>(let t0 (seconds) (sleep 1) (days-since t0)) 1/86400 |
time expr
Executes
expr and prints how long it took to execute. |
>(time (sleep 0.1)) time: 103 msec. nil |
jtime expr
Executes
expr, prints how long it took to execute, and returns the symbol ok. |
>(jtime (sleep 0.1)) time: 103 msec. ok |
time10 expr
Executes
expr 10 times and prints how long it took in total to execute. |
>(time10 (sleep 0.1)) time: 1031 msec. nil |
cache timef valf
Returns a caching procedure.
timef is a function that returns the cache lifetime in seconds. valf is a function that returns the value to be cached. |
>(cache (fn () 5) (fn () "val")) #<procedure> |
Copyright 2008 Ken Shirriff.