roughtime.googlesource.com/roughtime.git@v0.0.0-20201210012726-dd529367052d/clock_linux.cc (about)

     1  /* Copyright 2016 The Roughtime Authors.
     2   *
     3   * Licensed under the Apache License, Version 2.0 (the "License");
     4   * you may not use this file except in compliance with the License.
     5   * You may obtain a copy of the License at
     6   *
     7   *   http://www.apache.org/licenses/LICENSE-2.0
     8   *
     9   * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License. */
    14  
    15  
    16  #if defined(__linux) || defined (__Fuchsia__)
    17  
    18  #include <stdint.h>
    19  #include <stdlib.h>
    20  #include <time.h>
    21  
    22  namespace roughtime {
    23  
    24  // TimeUs returns the current value of the specified clock in microseconds.
    25  static uint64_t TimeUs(clockid_t clock) {
    26    struct timespec tv;
    27    if (clock_gettime(clock, &tv)) {
    28      abort();
    29    }
    30  
    31    uint64_t ret = tv.tv_sec;
    32    ret *= 1000000;
    33    ret += tv.tv_nsec / 1000;
    34    return ret;
    35  }
    36  
    37  // MonotonicUs returns the value of the monotonic clock in microseconds.
    38  uint64_t MonotonicUs() { return TimeUs(CLOCK_MONOTONIC); }
    39  
    40  // MonotonicUs returns the value of the realtime clock in microseconds.
    41  uint64_t RealtimeUs() { return TimeUs(CLOCK_REALTIME); }
    42  
    43  }  // namespace roughtime
    44  
    45  #endif  // __linux