Home | History | Annotate | Download | only in jni
      1 // Copyright 2017 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "time_utils.h"
      6 
      7 #include <sys/time.h>
      8 #include <sys/timerfd.h>
      9 #include <time.h>
     10 
     11 #include "logging.h"
     12 
     13 namespace time_utils {
     14 
     15 uint64_t GetTimestamp() {
     16   struct timespec ts = {};
     17   CHECK(clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0);
     18   return ts.tv_sec * 1000 + ts.tv_nsec / 1000000ul;
     19 }
     20 
     21 PeriodicTimer::PeriodicTimer(int interval_ms) : interval_ms_(interval_ms) {
     22   timer_fd_ = -1;
     23 }
     24 
     25 PeriodicTimer::~PeriodicTimer() {
     26   Stop();
     27 }
     28 
     29 void PeriodicTimer::Start() {
     30   Stop();
     31   timer_fd_ = timerfd_create(CLOCK_MONOTONIC, 0);
     32   CHECK(timer_fd_ >= 0);
     33   int sec = interval_ms_ / 1000;
     34   int nsec = (interval_ms_ % 1000) * 1000000;
     35   struct itimerspec ts = {};
     36   ts.it_value.tv_nsec = nsec;
     37   ts.it_value.tv_sec = sec;
     38   ts.it_interval.tv_nsec = nsec;
     39   ts.it_interval.tv_sec = sec;
     40   CHECK(timerfd_settime(timer_fd_, 0, &ts, nullptr) == 0);
     41 }
     42 
     43 void PeriodicTimer::Stop() {
     44   if (timer_fd_ < 0)
     45     return;
     46   close(timer_fd_);
     47   timer_fd_ = -1;
     48 }
     49 
     50 bool PeriodicTimer::Wait() {
     51   if (timer_fd_ < 0)
     52     return false;  // Not started yet.
     53   uint64_t stub = 0;
     54   int res = read(timer_fd_, &stub, sizeof(stub));
     55   if (res < 0 && errno == EBADF)
     56     return false;  // Interrupted by Stop().
     57   CHECK(res > 0);
     58   return true;
     59 }
     60 
     61 }  // namespace time_utils
     62