time_darwin.odin 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package time
  2. foreign import libc "system:c"
  3. TimeSpec :: struct {
  4. tv_sec : i64, /* seconds */
  5. tv_nsec : i64, /* nanoseconds */
  6. };
  7. CLOCK_SYSTEM :: 0;
  8. CLOCK_CALENDAR :: 1;
  9. IS_SUPPORTED :: true;
  10. foreign libc {
  11. @(link_name="clock_gettime") _clock_gettime :: proc(clock_id: u64, timespec: ^TimeSpec) ---;
  12. @(link_name="nanosleep") _nanosleep :: proc(requested: ^TimeSpec, remaining: ^TimeSpec) -> int ---;
  13. @(link_name="sleep") _sleep :: proc(seconds: u64) -> int ---;
  14. }
  15. clock_gettime :: proc(clock_id: u64) -> TimeSpec {
  16. ts : TimeSpec;
  17. _clock_gettime(clock_id, &ts);
  18. return ts;
  19. }
  20. now :: proc() -> Time {
  21. time_spec_now := clock_gettime(CLOCK_SYSTEM);
  22. ns := time_spec_now.tv_sec * 1e9 + time_spec_now.tv_nsec;
  23. return Time{_nsec=ns};
  24. }
  25. seconds_since_boot :: proc() -> f64 {
  26. ts_boottime := clock_gettime(CLOCK_SYSTEM);
  27. return f64(ts_boottime.tv_sec) + f64(ts_boottime.tv_nsec) / 1e9;
  28. }
  29. sleep :: proc(d: Duration) {
  30. ds := duration_seconds(d);
  31. seconds := u64(ds);
  32. nanoseconds := i64((ds - f64(seconds)) * 1e9);
  33. if seconds > 0 do _sleep(seconds);
  34. if nanoseconds > 0 do nanosleep(nanoseconds);
  35. }
  36. nanosleep :: proc(nanoseconds: i64) -> int {
  37. assert(nanoseconds <= 999999999);
  38. requested, remaining : TimeSpec;
  39. requested = TimeSpec{tv_nsec = nanoseconds};
  40. return _nanosleep(&requested, &remaining);
  41. }