[libc-commits] [libc] [libc][NFC] adjust time related implementations (PR #91485)

Schrodinger ZHU Yifan via libc-commits libc-commits at lists.llvm.org
Wed May 8 08:13:43 PDT 2024


================
@@ -21,8 +21,30 @@
 namespace LIBC_NAMESPACE {
 namespace internal {
 
-LIBC_INLINE ErrorOr<int> clock_gettimeimpl(clockid_t clockid,
-                                           struct timespec *ts) {
+namespace time_units {
----------------
SchrodingerZhu wrote:

I wonder that is the most suitable place to providing all these time related stuffs, which are subject to heavy reuse.

I still have two more functions flying around. Not sure where is the best places to put them in.
```cpp
LIBC_INLINE timespec convert_clock(timespec input, clockid_t from,
                                   clockid_t to) {
  timespec from_time;
  timespec to_time;
  timespec output;
  internal::clock_gettimeimpl(from, &from_time);
  internal::clock_gettimeimpl(to, &to_time);
  output.tv_sec = input.tv_sec - from_time.tv_sec + to_time.tv_sec;
  output.tv_nsec = input.tv_nsec - from_time.tv_nsec + to_time.tv_nsec;

  if (output.tv_nsec > 1'000'000'000) {
    output.tv_sec++;
    output.tv_nsec -= 1'000'000'000;
  } else if (output.tv_nsec < 0) {
    output.tv_sec--;
    output.tv_nsec += 1'000'000'000;
  }
  return output;
}
```
```cpp
struct Timeout {
   timespec abs_time;
   bool is_realtime;
};

LIBC_INLINE int check_timespec(cpp::optional<Timeout> &timeout) {
    if (!timeout)
      return 0;
    if (timeout->abs_time.tv_nsec < 0 ||
        timeout->abs_time.tv_nsec >= 1'000'000'000)
      return EINVAL;
    if (timeout->abs_time.tv_sec < 0)
      return LockResult::Timeout;
 #ifdef LIBC_OPT_CONVERT_REALTIME_TO_MONOTONIC_IN_LOCKS
    if (timeout->is_realtime) {
      timeout->abs_time =
          convert_clock(timeout->abs_time, CLOCK_REALTIME, CLOCK_MONOTONIC);
      timeout->is_realtime = false;
    }
 #endif // LIBC_OPT_CONVERT_REALTIME_TO_MONOTONIC_IN_LOCKS
    return 0;
  }
  ```

https://github.com/llvm/llvm-project/pull/91485


More information about the libc-commits mailing list