xref: /llvm-project-15.0.7/libcxx/src/chrono.cpp (revision ef2cdfe3)
1 //===------------------------- chrono.cpp ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #if defined(__MVS__)
10 // As part of monotonic clock support on z/OS we need macro _LARGE_TIME_API
11 // to be defined before any system header to include definition of struct timespec64.
12 #define _LARGE_TIME_API
13 #endif
14 
15 #include "chrono"
16 #include "cerrno"        // errno
17 #include "system_error"  // __throw_system_error
18 
19 #if defined(__MVS__)
20 #include <__support/ibm/gettod_zos.h> // gettimeofdayMonotonic
21 #endif
22 
23 #include <time.h>        // clock_gettime and CLOCK_{MONOTONIC,REALTIME,MONOTONIC_RAW}
24 #include "include/apple_availability.h"
25 
26 #if __has_include(<unistd.h>)
27 # include <unistd.h>
28 #endif
29 
30 #if __has_include(<sys/time.h>)
31 # include <sys/time.h> // for gettimeofday and timeval
32 #endif
33 
34 #if !defined(__APPLE__) && defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
35 # define _LIBCPP_USE_CLOCK_GETTIME
36 #endif
37 
38 #if defined(_LIBCPP_WIN32API)
39 #  define WIN32_LEAN_AND_MEAN
40 #  define VC_EXTRA_LEAN
41 #  include <windows.h>
42 #  if _WIN32_WINNT >= _WIN32_WINNT_WIN8
43 #    include <winapifamily.h>
44 #  endif
45 #endif // defined(_LIBCPP_WIN32API)
46 
47 #if __has_include(<mach/mach_time.h>)
48 # include <mach/mach_time.h>
49 #endif
50 
51 #if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
52 #  pragma comment(lib, "rt")
53 #endif
54 
55 _LIBCPP_BEGIN_NAMESPACE_STD
56 
57 namespace chrono
58 {
59 
60 //
61 // system_clock
62 //
63 
64 #if defined(_LIBCPP_WIN32API)
65 
66 #if _WIN32_WINNT < _WIN32_WINNT_WIN8
67 
68 namespace {
69 
70 typedef void(WINAPI *GetSystemTimeAsFileTimePtr)(LPFILETIME);
71 
72 class GetSystemTimeInit {
73 public:
74   GetSystemTimeInit() {
75     fp = (GetSystemTimeAsFileTimePtr)GetProcAddress(
76         GetModuleHandleW(L"kernel32.dll"), "GetSystemTimePreciseAsFileTime");
77     if (fp == nullptr)
78       fp = GetSystemTimeAsFileTime;
79   }
80   GetSystemTimeAsFileTimePtr fp;
81 };
82 
83 GetSystemTimeInit GetSystemTimeAsFileTimeFunc _LIBCPP_INIT_PRIORITY_MAX;
84 } // namespace
85 
86 #endif
87 
88 static system_clock::time_point __libcpp_system_clock_now() {
89   // FILETIME is in 100ns units
90   using filetime_duration =
91       _VSTD::chrono::duration<__int64,
92                               _VSTD::ratio_multiply<_VSTD::ratio<100, 1>,
93                                                     nanoseconds::period>>;
94 
95   // The Windows epoch is Jan 1 1601, the Unix epoch Jan 1 1970.
96   static _LIBCPP_CONSTEXPR const seconds nt_to_unix_epoch{11644473600};
97 
98   FILETIME ft;
99 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8 && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)) || \
100     (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
101   GetSystemTimePreciseAsFileTime(&ft);
102 #elif !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
103   GetSystemTimeAsFileTime(&ft);
104 #else
105   GetSystemTimeAsFileTimeFunc.fp(&ft);
106 #endif
107 
108   filetime_duration d{(static_cast<__int64>(ft.dwHighDateTime) << 32) |
109                        static_cast<__int64>(ft.dwLowDateTime)};
110   return system_clock::time_point(duration_cast<system_clock::duration>(d - nt_to_unix_epoch));
111 }
112 
113 #elif defined(CLOCK_REALTIME) && defined(_LIBCPP_USE_CLOCK_GETTIME)
114 
115 static system_clock::time_point __libcpp_system_clock_now() {
116   struct timespec tp;
117   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
118     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
119   return system_clock::time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
120 }
121 
122 #else
123 
124 static system_clock::time_point __libcpp_system_clock_now() {
125     timeval tv;
126     gettimeofday(&tv, 0);
127     return system_clock::time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
128 }
129 
130 #endif
131 
132 const bool system_clock::is_steady;
133 
134 system_clock::time_point
135 system_clock::now() noexcept
136 {
137     return __libcpp_system_clock_now();
138 }
139 
140 time_t
141 system_clock::to_time_t(const time_point& t) noexcept
142 {
143     return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
144 }
145 
146 system_clock::time_point
147 system_clock::from_time_t(time_t t) noexcept
148 {
149     return system_clock::time_point(seconds(t));
150 }
151 
152 //
153 // steady_clock
154 //
155 // Warning:  If this is not truly steady, then it is non-conforming.  It is
156 //  better for it to not exist and have the rest of libc++ use system_clock
157 //  instead.
158 //
159 
160 #ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
161 
162 #if defined(__APPLE__)
163 
164 // TODO(ldionne):
165 // This old implementation of steady_clock is retained until Chrome drops supports
166 // for macOS < 10.12. The issue is that they link libc++ statically into their
167 // application, which means that libc++ must support being built for such deployment
168 // targets. See https://llvm.org/D74489 for details.
169 #if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101200) || \
170     (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 100000) || \
171     (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 100000) || \
172     (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 30000)
173 # define _LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME
174 #endif
175 
176 #if defined(_LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME)
177 
178 //   mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of
179 //   nanoseconds since the computer booted up.  MachInfo.numer and MachInfo.denom
180 //   are run time constants supplied by the OS.  This clock has no relationship
181 //   to the Gregorian calendar.  It's main use is as a high resolution timer.
182 
183 // MachInfo.numer / MachInfo.denom is often 1 on the latest equipment.  Specialize
184 //   for that case as an optimization.
185 
186 static steady_clock::rep steady_simplified() {
187     return static_cast<steady_clock::rep>(mach_absolute_time());
188 }
189 static double compute_steady_factor() {
190     mach_timebase_info_data_t MachInfo;
191     mach_timebase_info(&MachInfo);
192     return static_cast<double>(MachInfo.numer) / MachInfo.denom;
193 }
194 
195 static steady_clock::rep steady_full() {
196     static const double factor = compute_steady_factor();
197     return static_cast<steady_clock::rep>(mach_absolute_time() * factor);
198 }
199 
200 typedef steady_clock::rep (*FP)();
201 
202 static FP init_steady_clock() {
203     mach_timebase_info_data_t MachInfo;
204     mach_timebase_info(&MachInfo);
205     if (MachInfo.numer == MachInfo.denom)
206         return &steady_simplified;
207     return &steady_full;
208 }
209 
210 static steady_clock::time_point __libcpp_steady_clock_now() {
211     static FP fp = init_steady_clock();
212     return steady_clock::time_point(steady_clock::duration(fp()));
213 }
214 
215 #else // vvvvv default behavior for Apple platforms  vvvvv
216 
217 // On Apple platforms, only CLOCK_UPTIME_RAW, CLOCK_MONOTONIC_RAW or
218 // mach_absolute_time are able to time functions in the nanosecond range.
219 // Furthermore, only CLOCK_MONOTONIC_RAW is truly monotonic, because it
220 // also counts cycles when the system is asleep. Thus, it is the only
221 // acceptable implementation of steady_clock.
222 static steady_clock::time_point __libcpp_steady_clock_now() {
223     struct timespec tp;
224     if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp))
225         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed");
226     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
227 }
228 
229 #endif
230 
231 #elif defined(_LIBCPP_WIN32API)
232 
233 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx says:
234 //    If the function fails, the return value is zero. <snip>
235 //    On systems that run Windows XP or later, the function will always succeed
236 //      and will thus never return zero.
237 
238 static LARGE_INTEGER
239 __QueryPerformanceFrequency()
240 {
241     LARGE_INTEGER val;
242     (void) QueryPerformanceFrequency(&val);
243     return val;
244 }
245 
246 static steady_clock::time_point __libcpp_steady_clock_now() {
247   static const LARGE_INTEGER freq = __QueryPerformanceFrequency();
248 
249   LARGE_INTEGER counter;
250   (void) QueryPerformanceCounter(&counter);
251   auto seconds = counter.QuadPart / freq.QuadPart;
252   auto fractions = counter.QuadPart % freq.QuadPart;
253   auto dur = seconds * nano::den + fractions * nano::den / freq.QuadPart;
254   return steady_clock::time_point(steady_clock::duration(dur));
255 }
256 
257 #elif defined(__MVS__)
258 
259 static steady_clock::time_point __libcpp_steady_clock_now() {
260   struct timespec64 ts;
261   if (0 != gettimeofdayMonotonic(&ts))
262     __throw_system_error(errno, "failed to obtain time of day");
263 
264   return steady_clock::time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
265 }
266 
267 #elif defined(CLOCK_MONOTONIC)
268 
269 static steady_clock::time_point __libcpp_steady_clock_now() {
270     struct timespec tp;
271     if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
272         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
273     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
274 }
275 
276 #else
277 #   error "Monotonic clock not implemented on this platform"
278 #endif
279 
280 const bool steady_clock::is_steady;
281 
282 steady_clock::time_point
283 steady_clock::now() noexcept
284 {
285     return __libcpp_steady_clock_now();
286 }
287 
288 #endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
289 
290 }
291 
292 _LIBCPP_END_NAMESPACE_STD
293