ocaml-multicore / eio

Effects-based direct-style IO for multicore OCaml
Other
560 stars 72 forks source link

enhancement: Implicit `clock` interface #506

Closed Nymphium closed 1 year ago

Nymphium commented 1 year ago

The function interfaces of the current Time require a clock, so we need to propagate the clock object from the eio main handler to the deeper call sites.

One opinion is to fetch clock by performing effect such as:

(* in Time module *)
type _ Effect.t += Get : #clock Effect.t
let now' () = now @@ Effect.perform Get

...

let measure f =
  let t1 = Eio.Time.now' () in
  f ();
  let t2 = Eio.Time.now' () in
  t2 -. t1

...

Eio_main.run @@ fun env ->
Eio.Time.run env#clock @@ fun () ->
measure (fun () -> print_endline "hello")
talex5 commented 1 year ago

Yes, Get_monotonic_clock works that way (used to implement Eio_unix.sleep).

Nymphium commented 1 year ago

Additionally, we can express it more commonly, such as switch passed to Fiber functions.

talex5 commented 1 year ago

You can do that, but it removes the benefit of using switches, which is to make the lifetimes clear. Creating a switch at the top-level and using it implicitly everywhere means functions can leak resources easily (e.g. forgetting to close a file).

Anyway, Eio doesn't prevent you from doing that, but it also doesn't want to encourage it.