Epoch in Lisp
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Lisp.
To run this program, you’ll need to install and load the local-time
library, which provides more comprehensive time manipulation functions than the built-in Common Lisp time functions.
In this Lisp version:
- We use
get-universal-time
to get the current time in seconds since the Unix epoch. - The
local-time:now
function from thelocal-time
library gives us a timestamp object similar to Go’stime.Now()
. - We multiply the seconds by 1000 and 1000000000 to get milliseconds and nanoseconds respectively.
- We use
local-time:unix-to-timestamp
to convert seconds back to a timestamp object. - For nanosecond precision, we split the nanoseconds into seconds and remaining nanoseconds.
Note that Common Lisp doesn’t have built-in functions for millisecond or nanosecond precision time, so we’re simulating them by multiplying the second value. For more precise timing, you might need to use system-specific functions or additional libraries.
Next, we’ll look at another time-related task: time parsing and formatting.