xref: /llvm-project-15.0.7/libcxx/src/chrono.cpp (revision 1b53413a)
13e519524SHoward Hinnant //===------------------------- chrono.cpp ---------------------------------===//
23e519524SHoward Hinnant //
357b08b09SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
457b08b09SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
557b08b09SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63e519524SHoward Hinnant //
73e519524SHoward Hinnant //===----------------------------------------------------------------------===//
8d3ac6ae7SEric Fiselier 
9cb2d2ae5SZbigniew Sarbinowski #if defined(__MVS__)
10cb2d2ae5SZbigniew Sarbinowski // As part of monotonic clock support on z/OS we need macro _LARGE_TIME_API
11cb2d2ae5SZbigniew Sarbinowski // to be defined before any system header to include definition of struct timespec64.
12cb2d2ae5SZbigniew Sarbinowski #define _LARGE_TIME_API
13cb2d2ae5SZbigniew Sarbinowski #endif
14cb2d2ae5SZbigniew Sarbinowski 
153e519524SHoward Hinnant #include "chrono"
164daa9f1eSMarshall Clow #include "cerrno"        // errno
174daa9f1eSMarshall Clow #include "system_error"  // __throw_system_error
18cb2d2ae5SZbigniew Sarbinowski 
19cb2d2ae5SZbigniew Sarbinowski #if defined(__MVS__)
20cb2d2ae5SZbigniew Sarbinowski #include <__support/ibm/gettod_zos.h> // gettimeofdayMonotonic
21cb2d2ae5SZbigniew Sarbinowski #endif
22cb2d2ae5SZbigniew Sarbinowski 
23babd3aefSLouis Dionne #include <time.h>        // clock_gettime and CLOCK_{MONOTONIC,REALTIME,MONOTONIC_RAW}
24c55ac105SEric Fiselier #include "include/apple_availability.h"
254f0f708bSEd Schouten 
264d25f445SJohn Brawn #if __has_include(<unistd.h>)
2759b31027SMara Sophie Grosch # include <unistd.h>
2859b31027SMara Sophie Grosch #endif
2959b31027SMara Sophie Grosch 
30f78bb4d8SHafiz Abid Qadeer #if __has_include(<sys/time.h>)
31f78bb4d8SHafiz Abid Qadeer # include <sys/time.h> // for gettimeofday and timeval
32f78bb4d8SHafiz Abid Qadeer #endif
33f78bb4d8SHafiz Abid Qadeer 
34d7550e5dSMartin Storsjö #if !defined(__APPLE__) && defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
35c55ac105SEric Fiselier # define _LIBCPP_USE_CLOCK_GETTIME
3659b31027SMara Sophie Grosch #endif
37e5423739SBruno Cardoso Lopes 
38b2826a1dSSaleem Abdulrasool #if defined(_LIBCPP_WIN32API)
396e3a0cc4SSaleem Abdulrasool #  define WIN32_LEAN_AND_MEAN
406e3a0cc4SSaleem Abdulrasool #  define VC_EXTRA_LEAN
411ec02625SEric Fiselier #  include <windows.h>
426e3a0cc4SSaleem Abdulrasool #  if _WIN32_WINNT >= _WIN32_WINNT_WIN8
436e3a0cc4SSaleem Abdulrasool #    include <winapifamily.h>
446e3a0cc4SSaleem Abdulrasool #  endif
45b2826a1dSSaleem Abdulrasool #endif // defined(_LIBCPP_WIN32API)
464f0f708bSEd Schouten 
47faa44078SLouis Dionne #if __has_include(<mach/mach_time.h>)
48faa44078SLouis Dionne # include <mach/mach_time.h>
49faa44078SLouis Dionne #endif
50faa44078SLouis Dionne 
51a9b5fff5SMichał Górny #if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
52996e62eeSPetr Hosek #  pragma comment(lib, "rt")
53996e62eeSPetr Hosek #endif
54996e62eeSPetr Hosek 
553e519524SHoward Hinnant _LIBCPP_BEGIN_NAMESPACE_STD
563e519524SHoward Hinnant 
573e519524SHoward Hinnant namespace chrono
583e519524SHoward Hinnant {
593e519524SHoward Hinnant 
602dec36e5SLouis Dionne //
613e519524SHoward Hinnant // system_clock
622dec36e5SLouis Dionne //
633e519524SHoward Hinnant 
64b2826a1dSSaleem Abdulrasool #if defined(_LIBCPP_WIN32API)
652dec36e5SLouis Dionne 
663ec634e6SSizhe Zhao #if _WIN32_WINNT < _WIN32_WINNT_WIN8
673ec634e6SSizhe Zhao 
683ec634e6SSizhe Zhao namespace {
693ec634e6SSizhe Zhao 
703ec634e6SSizhe Zhao typedef void(WINAPI *GetSystemTimeAsFileTimePtr)(LPFILETIME);
713ec634e6SSizhe Zhao 
723ec634e6SSizhe Zhao class GetSystemTimeInit {
733ec634e6SSizhe Zhao public:
743ec634e6SSizhe Zhao   GetSystemTimeInit() {
753ec634e6SSizhe Zhao     fp = (GetSystemTimeAsFileTimePtr)GetProcAddress(
763ec634e6SSizhe Zhao         GetModuleHandleW(L"kernel32.dll"), "GetSystemTimePreciseAsFileTime");
773ec634e6SSizhe Zhao     if (fp == nullptr)
783ec634e6SSizhe Zhao       fp = GetSystemTimeAsFileTime;
793ec634e6SSizhe Zhao   }
803ec634e6SSizhe Zhao   GetSystemTimeAsFileTimePtr fp;
813ec634e6SSizhe Zhao };
823ec634e6SSizhe Zhao 
83*1b53413aSMartin Storsjö # 83 "chrono.cpp" 1 3
843ec634e6SSizhe Zhao GetSystemTimeInit GetSystemTimeAsFileTimeFunc _LIBCPP_INIT_PRIORITY_MAX;
85*1b53413aSMartin Storsjö # 85 "chrono.cpp" 2
863ec634e6SSizhe Zhao } // namespace
873ec634e6SSizhe Zhao 
883ec634e6SSizhe Zhao #endif
893ec634e6SSizhe Zhao 
902dec36e5SLouis Dionne static system_clock::time_point __libcpp_system_clock_now() {
91e91473c3SSaleem Abdulrasool   // FILETIME is in 100ns units
92e91473c3SSaleem Abdulrasool   using filetime_duration =
93e91473c3SSaleem Abdulrasool       _VSTD::chrono::duration<__int64,
94e91473c3SSaleem Abdulrasool                               _VSTD::ratio_multiply<_VSTD::ratio<100, 1>,
95e91473c3SSaleem Abdulrasool                                                     nanoseconds::period>>;
966e3a0cc4SSaleem Abdulrasool 
97e91473c3SSaleem Abdulrasool   // The Windows epoch is Jan 1 1601, the Unix epoch Jan 1 1970.
98d1c346a4SSaleem Abdulrasool   static _LIBCPP_CONSTEXPR const seconds nt_to_unix_epoch{11644473600};
99e91473c3SSaleem Abdulrasool 
100e91473c3SSaleem Abdulrasool   FILETIME ft;
1013ec634e6SSizhe Zhao #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8 && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)) || \
1023ec634e6SSizhe Zhao     (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
103e91473c3SSaleem Abdulrasool   GetSystemTimePreciseAsFileTime(&ft);
1043ec634e6SSizhe Zhao #elif !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
105e91473c3SSaleem Abdulrasool   GetSystemTimeAsFileTime(&ft);
1063ec634e6SSizhe Zhao #else
1073ec634e6SSizhe Zhao   GetSystemTimeAsFileTimeFunc.fp(&ft);
1086e3a0cc4SSaleem Abdulrasool #endif
109e91473c3SSaleem Abdulrasool 
110e91473c3SSaleem Abdulrasool   filetime_duration d{(static_cast<__int64>(ft.dwHighDateTime) << 32) |
111e91473c3SSaleem Abdulrasool                        static_cast<__int64>(ft.dwLowDateTime)};
1122dec36e5SLouis Dionne   return system_clock::time_point(duration_cast<system_clock::duration>(d - nt_to_unix_epoch));
1132dec36e5SLouis Dionne }
1142dec36e5SLouis Dionne 
1152dec36e5SLouis Dionne #elif defined(CLOCK_REALTIME) && defined(_LIBCPP_USE_CLOCK_GETTIME)
1162dec36e5SLouis Dionne 
1172dec36e5SLouis Dionne static system_clock::time_point __libcpp_system_clock_now() {
1184f0f708bSEd Schouten   struct timespec tp;
1194f0f708bSEd Schouten   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
1204f0f708bSEd Schouten     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
1212dec36e5SLouis Dionne   return system_clock::time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
1222dec36e5SLouis Dionne }
1232dec36e5SLouis Dionne 
124e5423739SBruno Cardoso Lopes #else
1252dec36e5SLouis Dionne 
1262dec36e5SLouis Dionne static system_clock::time_point __libcpp_system_clock_now() {
1273e519524SHoward Hinnant     timeval tv;
1283e519524SHoward Hinnant     gettimeofday(&tv, 0);
1292dec36e5SLouis Dionne     return system_clock::time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
1302dec36e5SLouis Dionne }
1312dec36e5SLouis Dionne 
132f78bb4d8SHafiz Abid Qadeer #endif
1332dec36e5SLouis Dionne 
1342dec36e5SLouis Dionne const bool system_clock::is_steady;
1352dec36e5SLouis Dionne 
1362dec36e5SLouis Dionne system_clock::time_point
1375601305fSLouis Dionne system_clock::now() noexcept
1382dec36e5SLouis Dionne {
1392dec36e5SLouis Dionne     return __libcpp_system_clock_now();
1403e519524SHoward Hinnant }
1413e519524SHoward Hinnant 
1423e519524SHoward Hinnant time_t
1435601305fSLouis Dionne system_clock::to_time_t(const time_point& t) noexcept
1443e519524SHoward Hinnant {
1453e519524SHoward Hinnant     return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
1463e519524SHoward Hinnant }
1473e519524SHoward Hinnant 
1483e519524SHoward Hinnant system_clock::time_point
1495601305fSLouis Dionne system_clock::from_time_t(time_t t) noexcept
1503e519524SHoward Hinnant {
1513e519524SHoward Hinnant     return system_clock::time_point(seconds(t));
1523e519524SHoward Hinnant }
1533e519524SHoward Hinnant 
1542dec36e5SLouis Dionne //
1553dc6455fSHoward Hinnant // steady_clock
1564f0f708bSEd Schouten //
1574f0f708bSEd Schouten // Warning:  If this is not truly steady, then it is non-conforming.  It is
1584f0f708bSEd Schouten //  better for it to not exist and have the rest of libc++ use system_clock
1594f0f708bSEd Schouten //  instead.
1602dec36e5SLouis Dionne //
1613e519524SHoward Hinnant 
1622dec36e5SLouis Dionne #ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
16316694b5dSHoward Hinnant 
16478f51f95SSaleem Abdulrasool #if defined(__APPLE__)
1654f0f708bSEd Schouten 
166faa44078SLouis Dionne // TODO(ldionne):
167faa44078SLouis Dionne // This old implementation of steady_clock is retained until Chrome drops supports
168faa44078SLouis Dionne // for macOS < 10.12. The issue is that they link libc++ statically into their
169faa44078SLouis Dionne // application, which means that libc++ must support being built for such deployment
170faa44078SLouis Dionne // targets. See https://llvm.org/D74489 for details.
171faa44078SLouis Dionne #if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101200) || \
172faa44078SLouis Dionne     (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 100000) || \
173faa44078SLouis Dionne     (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 100000) || \
174faa44078SLouis Dionne     (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 30000)
175faa44078SLouis Dionne # define _LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME
176faa44078SLouis Dionne #endif
177faa44078SLouis Dionne 
178faa44078SLouis Dionne #if defined(_LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME)
179faa44078SLouis Dionne 
180faa44078SLouis Dionne //   mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of
181faa44078SLouis Dionne //   nanoseconds since the computer booted up.  MachInfo.numer and MachInfo.denom
182faa44078SLouis Dionne //   are run time constants supplied by the OS.  This clock has no relationship
183faa44078SLouis Dionne //   to the Gregorian calendar.  It's main use is as a high resolution timer.
184faa44078SLouis Dionne 
185faa44078SLouis Dionne // MachInfo.numer / MachInfo.denom is often 1 on the latest equipment.  Specialize
186faa44078SLouis Dionne //   for that case as an optimization.
187faa44078SLouis Dionne 
188faa44078SLouis Dionne static steady_clock::rep steady_simplified() {
189faa44078SLouis Dionne     return static_cast<steady_clock::rep>(mach_absolute_time());
190faa44078SLouis Dionne }
191faa44078SLouis Dionne static double compute_steady_factor() {
192faa44078SLouis Dionne     mach_timebase_info_data_t MachInfo;
193faa44078SLouis Dionne     mach_timebase_info(&MachInfo);
194faa44078SLouis Dionne     return static_cast<double>(MachInfo.numer) / MachInfo.denom;
195faa44078SLouis Dionne }
196faa44078SLouis Dionne 
197faa44078SLouis Dionne static steady_clock::rep steady_full() {
198faa44078SLouis Dionne     static const double factor = compute_steady_factor();
199faa44078SLouis Dionne     return static_cast<steady_clock::rep>(mach_absolute_time() * factor);
200faa44078SLouis Dionne }
201faa44078SLouis Dionne 
202faa44078SLouis Dionne typedef steady_clock::rep (*FP)();
203faa44078SLouis Dionne 
204faa44078SLouis Dionne static FP init_steady_clock() {
205faa44078SLouis Dionne     mach_timebase_info_data_t MachInfo;
206faa44078SLouis Dionne     mach_timebase_info(&MachInfo);
207faa44078SLouis Dionne     if (MachInfo.numer == MachInfo.denom)
208faa44078SLouis Dionne         return &steady_simplified;
209faa44078SLouis Dionne     return &steady_full;
210faa44078SLouis Dionne }
211faa44078SLouis Dionne 
212faa44078SLouis Dionne static steady_clock::time_point __libcpp_steady_clock_now() {
213faa44078SLouis Dionne     static FP fp = init_steady_clock();
214faa44078SLouis Dionne     return steady_clock::time_point(steady_clock::duration(fp()));
215faa44078SLouis Dionne }
216faa44078SLouis Dionne 
217faa44078SLouis Dionne #else // vvvvv default behavior for Apple platforms  vvvvv
218faa44078SLouis Dionne 
219babd3aefSLouis Dionne // On Apple platforms, only CLOCK_UPTIME_RAW, CLOCK_MONOTONIC_RAW or
220babd3aefSLouis Dionne // mach_absolute_time are able to time functions in the nanosecond range.
221babd3aefSLouis Dionne // Furthermore, only CLOCK_MONOTONIC_RAW is truly monotonic, because it
222babd3aefSLouis Dionne // also counts cycles when the system is asleep. Thus, it is the only
223babd3aefSLouis Dionne // acceptable implementation of steady_clock.
2242dec36e5SLouis Dionne static steady_clock::time_point __libcpp_steady_clock_now() {
225e5423739SBruno Cardoso Lopes     struct timespec tp;
2268bec8927SLouis Dionne     if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp))
2278bec8927SLouis Dionne         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed");
2282dec36e5SLouis Dionne     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
229e5423739SBruno Cardoso Lopes }
230e5423739SBruno Cardoso Lopes 
231faa44078SLouis Dionne #endif
232faa44078SLouis Dionne 
233b2826a1dSSaleem Abdulrasool #elif defined(_LIBCPP_WIN32API)
23478f51f95SSaleem Abdulrasool 
235ecad92b0SMarshall Clow // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx says:
236ecad92b0SMarshall Clow //    If the function fails, the return value is zero. <snip>
237ecad92b0SMarshall Clow //    On systems that run Windows XP or later, the function will always succeed
238ecad92b0SMarshall Clow //      and will thus never return zero.
239ecad92b0SMarshall Clow 
240ecad92b0SMarshall Clow static LARGE_INTEGER
241ecad92b0SMarshall Clow __QueryPerformanceFrequency()
242ecad92b0SMarshall Clow {
243ecad92b0SMarshall Clow     LARGE_INTEGER val;
244ecad92b0SMarshall Clow     (void) QueryPerformanceFrequency(&val);
245ecad92b0SMarshall Clow     return val;
246ecad92b0SMarshall Clow }
247ecad92b0SMarshall Clow 
2482dec36e5SLouis Dionne static steady_clock::time_point __libcpp_steady_clock_now() {
249ecad92b0SMarshall Clow   static const LARGE_INTEGER freq = __QueryPerformanceFrequency();
25078f51f95SSaleem Abdulrasool 
25168ad5c34SMarshall Clow   LARGE_INTEGER counter;
25268ad5c34SMarshall Clow   (void) QueryPerformanceCounter(&counter);
25302f1d28eSMartin Storsjö   auto seconds = counter.QuadPart / freq.QuadPart;
25402f1d28eSMartin Storsjö   auto fractions = counter.QuadPart % freq.QuadPart;
25502f1d28eSMartin Storsjö   auto dur = seconds * nano::den + fractions * nano::den / freq.QuadPart;
25602f1d28eSMartin Storsjö   return steady_clock::time_point(steady_clock::duration(dur));
25778f51f95SSaleem Abdulrasool }
25878f51f95SSaleem Abdulrasool 
259cb2d2ae5SZbigniew Sarbinowski #elif defined(__MVS__)
260cb2d2ae5SZbigniew Sarbinowski 
261cb2d2ae5SZbigniew Sarbinowski static steady_clock::time_point __libcpp_steady_clock_now() {
262cb2d2ae5SZbigniew Sarbinowski   struct timespec64 ts;
263cb2d2ae5SZbigniew Sarbinowski   if (0 != gettimeofdayMonotonic(&ts))
264cb2d2ae5SZbigniew Sarbinowski     __throw_system_error(errno, "failed to obtain time of day");
265cb2d2ae5SZbigniew Sarbinowski 
266cb2d2ae5SZbigniew Sarbinowski   return steady_clock::time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
267cb2d2ae5SZbigniew Sarbinowski }
268cb2d2ae5SZbigniew Sarbinowski 
26978f51f95SSaleem Abdulrasool #elif defined(CLOCK_MONOTONIC)
27078f51f95SSaleem Abdulrasool 
2712dec36e5SLouis Dionne static steady_clock::time_point __libcpp_steady_clock_now() {
27278f51f95SSaleem Abdulrasool     struct timespec tp;
27378f51f95SSaleem Abdulrasool     if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
27478f51f95SSaleem Abdulrasool         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
2752dec36e5SLouis Dionne     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
27678f51f95SSaleem Abdulrasool }
27778f51f95SSaleem Abdulrasool 
2784f0f708bSEd Schouten #else
2792dec36e5SLouis Dionne #   error "Monotonic clock not implemented on this platform"
2804f0f708bSEd Schouten #endif
281128ba719SHoward Hinnant 
2822dec36e5SLouis Dionne const bool steady_clock::is_steady;
2832dec36e5SLouis Dionne 
2842dec36e5SLouis Dionne steady_clock::time_point
2855601305fSLouis Dionne steady_clock::now() noexcept
2862dec36e5SLouis Dionne {
2872dec36e5SLouis Dionne     return __libcpp_steady_clock_now();
2882dec36e5SLouis Dionne }
2892dec36e5SLouis Dionne 
290c59e5851SJonathan Roelofs #endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
291c59e5851SJonathan Roelofs 
2923e519524SHoward Hinnant }
2933e519524SHoward Hinnant 
2943e519524SHoward Hinnant _LIBCPP_END_NAMESPACE_STD
295