hyf

Context-aware query service for Radroots
git clone https://radroots.dev/git/hyf.git
Log | Files | Refs | README | LICENSE

clock.mojo (1151B)


      1 from std.ffi import c_long, external_call
      2 from std.time import perf_counter_ns
      3 
      4 
      5 @fieldwise_init
      6 struct Clock(Copyable, Movable):
      7     var wall_epoch_seconds: Int
      8     var monotonic_ns: Int
      9 
     10 
     11 def fixed_clock(wall_epoch_seconds: Int, monotonic_ns: Int) -> Clock:
     12     return Clock(
     13         wall_epoch_seconds=wall_epoch_seconds, monotonic_ns=monotonic_ns
     14     )
     15 
     16 
     17 def advance(clock: Clock, monotonic_delta_ns: Int) -> Clock:
     18     return Clock(
     19         wall_epoch_seconds=clock.wall_epoch_seconds,
     20         monotonic_ns=clock.monotonic_ns + monotonic_delta_ns,
     21     )
     22 
     23 
     24 def clock_wall_epoch_seconds(clock: Clock) -> Int:
     25     return clock.wall_epoch_seconds
     26 
     27 
     28 def clock_monotonic_ns(clock: Clock) -> Int:
     29     return clock.monotonic_ns
     30 
     31 
     32 def monotonic_elapsed_ns(start: Clock, end: Clock) -> Int:
     33     return end.monotonic_ns - start.monotonic_ns
     34 
     35 
     36 def system_wall_epoch_seconds() -> Int:
     37     return Int(external_call["time", c_long](0))
     38 
     39 
     40 def system_monotonic_ns() -> Int:
     41     return Int(perf_counter_ns())
     42 
     43 
     44 def system_clock() -> Clock:
     45     return Clock(
     46         wall_epoch_seconds=system_wall_epoch_seconds(),
     47         monotonic_ns=system_monotonic_ns(),
     48     )