roughtime.googlesource.com/roughtime.git@v0.0.0-20201210012726-dd529367052d/clock_macos.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(__APPLE__) 17 18 #include <mach/clock.h> 19 #include <mach/mach.h> 20 #include <stdint.h> 21 #include <stdlib.h> 22 #include <time.h> 23 24 namespace roughtime { 25 26 // TimeUs returns the current value of the specified clock in microseconds. 27 static uint64_t TimeUs(clock_id_t clock) { 28 clock_serv_t clock_ref; 29 mach_timespec_t tv; 30 31 if (host_get_clock_service(mach_host_self(), clock, &clock_ref) != 32 KERN_SUCCESS || 33 clock_get_time(clock_ref, &tv) != KERN_SUCCESS || 34 mach_port_deallocate(mach_task_self(), clock_ref) != KERN_SUCCESS) { 35 abort(); 36 } 37 38 uint64_t ret = tv.tv_sec; 39 ret *= 1000000; 40 ret += tv.tv_nsec / 1000; 41 return ret; 42 } 43 44 // MonotonicUs returns the value of the monotonic clock in microseconds. 45 uint64_t MonotonicUs() { return TimeUs(REALTIME_CLOCK); } 46 47 // MonotonicUs returns the value of the realtime clock in microseconds. 48 uint64_t RealtimeUs() { return TimeUs(CALENDAR_CLOCK); } 49 50 } // namespace roughtime 51 52 #endif // __linux