2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/portability/Time.h>
18 #include <folly/Likely.h>
24 template <typename _Rep, typename _Period>
25 static void duration_to_ts(
26 std::chrono::duration<_Rep, _Period> d,
27 struct timespec* ts) {
28 ts->tv_sec = std::chrono::duration_cast<std::chrono::seconds>(d).count();
29 ts->tv_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
30 d % std::chrono::seconds(1))
34 #if !FOLLY_HAVE_CLOCK_GETTIME
37 #include <mach/mach_init.h>
38 #include <mach/mach_port.h>
39 #include <mach/mach_time.h>
40 #include <mach/mach_types.h>
41 #include <mach/task.h>
42 #include <mach/thread_act.h>
43 #include <mach/vm_map.h>
45 static std::chrono::nanoseconds time_value_to_ns(time_value_t t) {
46 return std::chrono::seconds(t.seconds) +
47 std::chrono::microseconds(t.microseconds);
50 static int clock_process_cputime(struct timespec* ts) {
51 // Get CPU usage for live threads.
52 task_thread_times_info thread_times_info;
53 mach_msg_type_number_t thread_times_info_count;
54 TASK_THREAD_TIMES_INFO_COUNT;
55 kern_return_t kern_result = task_info(
57 TASK_THREAD_TIMES_INFO,
58 (thread_info_t)&thread_times_info,
59 &thread_times_info_count);
60 if (UNLIKELY(kern_result != KERN_SUCCESS)) {
64 // Get CPU usage for terminated threads.
65 mach_task_basic_info task_basic_info;
66 mach_msg_type_number_t task_basic_info_count = MACH_TASK_BASIC_INFO_COUNT;
67 kern_result = task_info(
70 (thread_info_t)&task_basic_info,
71 &task_basic_info_count);
72 if (UNLIKELY(kern_result != KERN_SUCCESS)) {
76 auto cputime = time_value_to_ns(thread_times_info.user_time) +
77 time_value_to_ns(thread_times_info.system_time) +
78 time_value_to_ns(task_basic_info.user_time) +
79 time_value_to_ns(task_basic_info.system_time);
80 duration_to_ts(cputime, ts);
84 static int clock_thread_cputime(struct timespec* ts) {
85 mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
86 thread_basic_info_data_t thread_info_data;
87 thread_act_t thread = mach_thread_self();
88 kern_return_t kern_result = thread_info(
89 thread, THREAD_BASIC_INFO, (thread_info_t)&thread_info_data, &count);
90 mach_port_deallocate(mach_task_self(), thread);
91 if (UNLIKELY(kern_result != KERN_SUCCESS)) {
94 auto cputime = time_value_to_ns(thread_info_data.system_time) +
95 time_value_to_ns(thread_info_data.user_time);
96 duration_to_ts(cputime, ts);
100 int clock_gettime(clockid_t clk_id, struct timespec* ts) {
102 case CLOCK_REALTIME: {
103 auto now = std::chrono::system_clock::now().time_since_epoch();
104 duration_to_ts(now, ts);
107 case CLOCK_MONOTONIC: {
108 auto now = std::chrono::steady_clock::now().time_since_epoch();
109 duration_to_ts(now, ts);
112 case CLOCK_PROCESS_CPUTIME_ID:
113 return clock_process_cputime(ts);
114 case CLOCK_THREAD_CPUTIME_ID:
115 return clock_thread_cputime(ts);
122 int clock_getres(clockid_t clk_id, struct timespec* ts) {
123 if (clk_id != CLOCK_MONOTONIC) {
127 static auto info = [] {
128 static mach_timebase_info_data_t info;
129 auto result = (mach_timebase_info(&info) == KERN_SUCCESS) ? &info : nullptr;
135 ts->tv_nsec = info->numer / info->denom;
139 #elif defined(_WIN32)
145 #include <folly/portability/Windows.h>
147 using unsigned_nanos = std::chrono::duration<uint64_t, std::nano>;
149 static unsigned_nanos filetimeToUnsignedNanos(FILETIME ft) {
151 i.HighPart = ft.dwHighDateTime;
152 i.LowPart = ft.dwLowDateTime;
154 // FILETIMEs are in units of 100ns.
155 return unsigned_nanos(i.QuadPart * 100);
158 static LARGE_INTEGER performanceFrequency() {
159 static auto result = [] {
161 // On Windows XP or later, this will never fail.
162 BOOL res = QueryPerformanceFrequency(&freq);
169 extern "C" int clock_getres(clockid_t clock_id, struct timespec* res) {
176 case CLOCK_MONOTONIC: {
177 LARGE_INTEGER freq = performanceFrequency();
178 if (freq.QuadPart == -1) {
183 static constexpr size_t kNsPerSec = 1000000000;
186 res->tv_nsec = (long)((kNsPerSec + (freq.QuadPart >> 1)) / freq.QuadPart);
187 if (res->tv_nsec < 1) {
195 case CLOCK_PROCESS_CPUTIME_ID:
196 case CLOCK_THREAD_CPUTIME_ID: {
197 DWORD adj, timeIncrement;
199 if (!GetSystemTimeAdjustment(&adj, &timeIncrement, &adjDisabled)) {
205 res->tv_nsec = timeIncrement * 100;
215 extern "C" int clock_gettime(clockid_t clock_id, struct timespec* tp) {
221 const auto unanosToTimespec = [](timespec* tp, unsigned_nanos t) -> int {
222 static constexpr unsigned_nanos one_sec(std::chrono::seconds(1));
223 tp->tv_sec = std::chrono::duration_cast<std::chrono::seconds>(t).count();
224 tp->tv_nsec = (t % one_sec).count();
228 FILETIME createTime, exitTime, kernalTime, userTime;
230 case CLOCK_REALTIME: {
231 auto now = std::chrono::system_clock::now().time_since_epoch();
232 duration_to_ts(now, tp);
235 case CLOCK_MONOTONIC: {
236 auto now = std::chrono::steady_clock::now().time_since_epoch();
237 duration_to_ts(now, tp);
240 case CLOCK_PROCESS_CPUTIME_ID: {
241 if (!GetProcessTimes(
251 return unanosToTimespec(
253 filetimeToUnsignedNanos(kernalTime) +
254 filetimeToUnsignedNanos(userTime));
256 case CLOCK_THREAD_CPUTIME_ID: {
267 return unanosToTimespec(
269 filetimeToUnsignedNanos(kernalTime) +
270 filetimeToUnsignedNanos(userTime));
279 #error No clock_gettime(3) compatibility wrapper available for this platform.
287 #include <folly/portability/Windows.h>
290 char* asctime_r(const tm* tm, char* buf) {
292 if (asctime_s(tmpBuf, tm)) {
295 // Nothing we can do if the buff is to small :(
296 return strcpy(buf, tmpBuf);
299 char* ctime_r(const time_t* t, char* buf) {
301 if (ctime_s(tmpBuf, 64, t)) {
304 // Nothing we can do if the buff is to small :(
305 return strcpy(buf, tmpBuf);
308 tm* gmtime_r(const time_t* t, tm* res) {
309 if (!gmtime_s(res, t)) {
315 tm* localtime_r(const time_t* t, tm* o) {
316 if (!localtime_s(o, t)) {
322 int nanosleep(const struct timespec* request, struct timespec* remain) {
323 Sleep((DWORD)((request->tv_sec * 1000) + (request->tv_nsec / 1000000)));
329 char* strptime(const char* __restrict s,
330 const char* __restrict f,
331 struct tm* __restrict tm) {
332 // Isn't the C++ standard lib nice? std::get_time is defined such that its
333 // format parameters are the exact same as strptime. Of course, we have to
334 // create a string stream first, and imbue it with the current C locale, and
335 // we also have to make sure we return the right things if it fails, or
336 // if it succeeds, but this is still far simpler an implementation than any
337 // of the versions in any of the C standard libraries.
338 std::istringstream input(s);
339 input.imbue(std::locale(setlocale(LC_ALL, nullptr)));
340 input >> std::get_time(tm, f);
344 return const_cast<char*>(s + input.tellg());