Epoch in OCaml
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 OCaml.
open Unix
let () =
let now = gettimeofday () in
Printf.printf "%f\n" now;
(* Get seconds since Unix epoch *)
let seconds = int_of_float now in
Printf.printf "%d\n" seconds;
(* Get milliseconds since Unix epoch *)
let milliseconds = int_of_float (now *. 1000.) in
Printf.printf "%d\n" milliseconds;
(* Get nanoseconds since Unix epoch *)
let nanoseconds = int_of_float (now *. 1e9) in
Printf.printf "%d\n" nanoseconds;
(* Convert seconds back to time *)
let time_from_seconds = localtime (float_of_int seconds) in
Printf.printf "%s\n" (string_of_tm time_from_seconds);
(* Convert nanoseconds back to time *)
let time_from_nanos = localtime (float_of_int seconds) in
Printf.printf "%s\n" (string_of_tm time_from_nanos)
In OCaml, we use the Unix
module to work with time-related functions. The gettimeofday
function returns the current time as a float representing seconds since the Unix epoch.
We can then use this value to calculate seconds, milliseconds, and nanoseconds. To convert back to a time structure, we use the localtime
function.
To run the program, save it as epoch.ml
and use the OCaml compiler:
$ ocamlc unix.cma epoch.ml -o epoch
$ ./epoch
1622547321.123456
1622547321
1622547321123
1622547321123456000
Tue Jun 1 12:15:21 2021
Tue Jun 1 12:15:21 2021
Note that the exact output will depend on when you run the program.
Next, we’ll look at another time-related task: time parsing and formatting.