1 /* 2 Copyright (c) DataStax, Inc 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 #include <unistd.h> 18 19 #if _POSIX_TIMERS > 0 20 21 #include "get_time.hpp" 22 23 #include <time.h> 24 25 namespace datastax { namespace internal { 26 27 class ClockInfo { 28 public: ClockInfo()29 ClockInfo() { 30 struct timespec res; 31 struct timespec tp; 32 supports_monotonic_ = 33 clock_getres(CLOCK_MONOTONIC, &res) == 0 && clock_gettime(CLOCK_MONOTONIC, &tp) == 0; 34 } 35 supports_monotonic()36 static bool supports_monotonic() { return supports_monotonic_; } 37 38 private: 39 static bool supports_monotonic_; 40 }; 41 42 bool ClockInfo::supports_monotonic_; 43 44 static ClockInfo __clock_info__; // Initializer 45 get_time_since_epoch_us()46uint64_t get_time_since_epoch_us() { 47 struct timespec ts; 48 clock_gettime(CLOCK_REALTIME, &ts); 49 return static_cast<uint64_t>(ts.tv_sec) * 1000000 + static_cast<uint64_t>(ts.tv_nsec) / 1000; 50 } 51 get_time_monotonic_ns()52uint64_t get_time_monotonic_ns() { 53 if (ClockInfo::supports_monotonic()) { 54 struct timespec tp; 55 clock_gettime(CLOCK_MONOTONIC, &tp); 56 return static_cast<uint64_t>(tp.tv_sec) * NANOSECONDS_PER_SECOND + 57 static_cast<uint64_t>(tp.tv_nsec); 58 } else { 59 return get_time_since_epoch_us() * NANOSECONDS_PER_MICROSECOND; 60 } 61 } 62 63 }} // namespace datastax::internal 64 65 #endif 66