roughtime.googlesource.com/roughtime.git@v0.0.0-20201210012726-dd529367052d/sys_time.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 #include "sys_time.h" 16 17 #if defined(__MACH__) 18 #include <sys/time.h> 19 #else 20 #include <time.h> 21 #endif 22 23 #include "logging.h" 24 25 namespace roughtime { 26 27 static const uint32_t kOneSecondRadius = 1000000; 28 29 SystemTimeSource::SystemTimeSource() {} 30 31 SystemTimeSource::~SystemTimeSource() {} 32 33 #if defined(__MACH__) 34 std::pair<rough_time_t, uint32_t> SystemTimeSource::Now() { 35 struct timeval tv; 36 ROUGHTIME_CHECK_EQ(0, gettimeofday(&tv, nullptr)); 37 uint64_t now = tv.tv_sec; 38 now *= 1000000; 39 now += tv.tv_usec; 40 41 return std::make_pair(now, kOneSecondRadius); 42 } 43 #else 44 std::pair<rough_time_t, uint32_t> SystemTimeSource::Now() { 45 struct timespec ts; 46 ROUGHTIME_CHECK_EQ(0, clock_gettime(CLOCK_REALTIME_COARSE, &ts)); 47 uint64_t now = ts.tv_sec; 48 now *= 1000000; 49 now += ts.tv_nsec / 1000; 50 51 return std::make_pair(now, kOneSecondRadius); 52 } 53 #endif 54 55 } // namespace roughtime