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