-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathwalltime.cc
269 lines (237 loc) · 8.75 KB
/
walltime.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright 2012 Google Inc. All Rights Reserved.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// Author: tkaftal@google.com (Tomasz Kaftal)
//
// The implementation of walltime functionalities.
#ifndef _GNU_SOURCE // gcc3 at least defines it on the command line
#define _GNU_SOURCE // Linux wants that for strptime in time.h
#endif
#include "yb/gutil/walltime.h"
#if defined(__APPLE__)
#include <mach/clock.h>
#include <mach/mach.h>
#endif // defined(__APPLE__)
#include <memory>
#include "yb/util/logging.h"
#include "yb/util/monotime.h"
#if defined(__APPLE__)
namespace walltime_internal {
GoogleOnceType timebase_info_once = GOOGLE_ONCE_INIT;
mach_timebase_info_data_t timebase_info;
void InitializeTimebaseInfo() {
CHECK_EQ(KERN_SUCCESS, mach_timebase_info(&timebase_info))
<< "unable to initialize mach_timebase_info";
}
} // namespace walltime_internal
#endif
// This is exactly like mktime() except it is guaranteed to return -1 on
// failure. Some versions of glibc allow mktime() to return negative
// values which the standard says are undefined. See the standard at
// http://www.opengroup.org/onlinepubs/007904875/basedefs/xbd_chap04.html
// under the heading "Seconds Since the Epoch".
static inline time_t gmktime(struct tm *tm) {
time_t rt = mktime(tm);
return rt < 0 ? time_t(-1) : rt;
}
void StringAppendStrftime(std::string* dst,
const char* format,
const struct tm* tm) {
char space[1024];
size_t result = strftime(space, sizeof(space), format, tm);
if (result > 0) {
// It fit
dst->append(space, result);
return;
}
size_t length = sizeof(space);
for (int sanity = 0; sanity < 5; ++sanity) {
length *= 2;
std::unique_ptr<char[]> buf(new char[length]);
result = strftime(buf.get(), length, format, tm);
if (result > 0) {
// It fit
dst->append(buf.get(), result);
return;
}
}
// sanity failure
return;
}
// Convert a "struct tm" interpreted as *GMT* into a time_t (technically
// a long since we can't include header files in header files bla bla bla).
// This is basically filling a hole in the standard library.
//
// There are several approaches to mkgmtime() implementation on the net,
// many of them wrong. Simply reimplementing the logic seems to be the
// simplest and most efficient, though it does reimplement calendar logic.
// The calculation is mostly straightforward; leap years are the main issue.
//
// Like gmktime() this method returns -1 on failure. Negative results
// are considered undefined by the standard so these cases are
// considered failures and thus return -1.
time_t mkgmtime(const struct tm *tm) {
// Month-to-day offset for non-leap-years.
static const int month_day[12] =
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
// Most of the calculation is easy; leap years are the main difficulty.
int month = tm->tm_mon % 12;
int year = tm->tm_year + tm->tm_mon / 12;
if (month < 0) { // Negative values % 12 are still negative.
month += 12;
--year;
}
// This is the number of Februaries since 1900.
const int year_for_leap = (month > 1) ? year + 1 : year;
time_t rt = tm->tm_sec // Seconds
+ 60 * (tm->tm_min // Minute = 60 seconds
+ 60 * (tm->tm_hour // Hour = 60 minutes
+ 24 * (month_day[month] + tm->tm_mday - 1 // Day = 24 hours
+ 365 * (year - 70) // Year = 365 days
+ (year_for_leap - 69) / 4 // Every 4 years is leap...
- (year_for_leap - 1) / 100 // Except centuries...
+ (year_for_leap + 299) / 400))); // Except 400s.
return rt < 0 ? -1 : rt;
}
bool WallTime_Parse_Timezone(const char* time_spec,
const char* format,
const struct tm* default_time,
bool local,
WallTime* result) {
struct tm split_time;
if (default_time) {
split_time = *default_time;
} else {
memset(&split_time, 0, sizeof(split_time));
}
const char* parsed = strptime(time_spec, format, &split_time);
if (parsed == nullptr) return false;
// If format ends with "%S", match fractional seconds
double fraction = 0.0;
char junk;
if ((*parsed == '.') &&
(strcmp(format + strlen(format) - 2, "%S") == 0) &&
(sscanf(parsed, "%lf%c", // NOLINT(runtime/printf)
&fraction, &junk) == 1)) {
parsed = format + strlen(format); // Parsed it all!
}
if (*parsed != '\0') return false;
// Convert into seconds since epoch. Adjust so it is interpreted
// w.r.t. the daylight-saving-state at the specified time.
split_time.tm_isdst = -1; // Ask gmktime() to find dst imfo
time_t ptime;
if (local) {
ptime = gmktime(&split_time);
} else {
ptime = mkgmtime(&split_time); // Returns time in GMT instead of local.
}
if (ptime == -1) return false;
*result = ptime;
*result += fraction;
return true;
}
WallTime WallTime_Now() {
#if defined(__APPLE__)
mach_timespec_t ts;
walltime_internal::GetCurrentTime(&ts);
return ts.tv_sec + ts.tv_nsec / static_cast<double>(1e9);
#else
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return ts.tv_sec + ts.tv_nsec / static_cast<double>(1e9);
#endif // defined(__APPLE__)
}
void StringAppendStrftime(std::string* dst,
const char* format,
time_t when,
bool local) {
struct tm tm;
bool conversion_error;
if (local) {
conversion_error = (localtime_r(&when, &tm) == nullptr);
} else {
conversion_error = (gmtime_r(&when, &tm) == nullptr);
}
if (conversion_error) {
// If we couldn't convert the time, don't append anything.
return;
}
StringAppendStrftime(dst, format, &tm);
}
std::string LocalTimeAsString() {
std::string ret;
StringAppendStrftime(&ret, "%Y-%m-%d %H:%M:%S %Z", time(nullptr), true);
return ret;
}
void GetThreadUserAndSysCpuTimeMicros(MicrosecondsInt64 *user, MicrosecondsInt64 *sys) {
#if defined(__APPLE__)
// See https://www.gnu.org/software/hurd/gnumach-doc/Thread-Information.html
// and Chromium base/time/time_mac.cc.
task_t thread = mach_thread_self();
if (thread == MACH_PORT_NULL) {
LOG(WARNING) << "Failed to get mach_thread_self()";
return;
}
mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
thread_basic_info_data_t thread_info_data;
kern_return_t result = thread_info(
thread,
THREAD_BASIC_INFO,
reinterpret_cast<thread_info_t>(&thread_info_data),
&thread_info_count);
if (result != KERN_SUCCESS) {
LOG(WARNING) << "Failed to get thread_info()";
return;
}
if (user) {
*user = thread_info_data.user_time.seconds * 1e6L + thread_info_data.user_time.microseconds;
}
if (sys) {
*sys = thread_info_data.system_time.seconds * 1e6L + thread_info_data.system_time.microseconds;
}
#else
struct rusage usage;
CHECK_EQ(0, getrusage(RUSAGE_THREAD, &usage));
if (user) {
*user = usage.ru_utime.tv_sec * 1e6L + usage.ru_utime.tv_usec;
}
if (sys) {
*sys = usage.ru_stime.tv_sec * 1e6L + usage.ru_stime.tv_usec;
}
#endif
}
uint64_t FastClockNanos() {
timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return ts.tv_sec * yb::MonoTime::kNanosecondsPerSecond + ts.tv_nsec;
}