xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Support/Chrono.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- llvm/Support/Chrono.h - Utilities for Timing Manipulation-*- C++ -*-===//
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 #ifndef LLVM_SUPPORT_CHRONO_H
10 #define LLVM_SUPPORT_CHRONO_H
11 
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/Support/FormatProviders.h"
14 
15 #include <chrono>
16 #include <ctime>
17 #include <ratio>
18 
19 namespace llvm {
20 
21 class raw_ostream;
22 
23 namespace sys {
24 
25 /// A time point on the system clock. This is provided for two reasons:
26 /// - to insulate us against subtle differences in behavior to differences in
27 ///   system clock precision (which is implementation-defined and differs
28 ///   between platforms).
29 /// - to shorten the type name
30 /// The default precision is nanoseconds. If you need a specific precision
31 /// specify it explicitly. If unsure, use the default. If you need a time point
32 /// on a clock other than the system_clock, use std::chrono directly.
33 template <typename D = std::chrono::nanoseconds>
34 using TimePoint = std::chrono::time_point<std::chrono::system_clock, D>;
35 
36 // utc_clock and utc_time are only available since C++20. Add enough code to
37 // support formatting date/time in UTC.
38 class UtcClock : public std::chrono::system_clock {};
39 
40 template <typename D = std::chrono::nanoseconds>
41 using UtcTime = std::chrono::time_point<UtcClock, D>;
42 
43 /// Convert a std::time_t to a UtcTime
toUtcTime(std::time_t T)44 inline UtcTime<std::chrono::seconds> toUtcTime(std::time_t T) {
45   using namespace std::chrono;
46   return UtcTime<seconds>(seconds(T));
47 }
48 
49 /// Convert a TimePoint to std::time_t
toTimeT(TimePoint<> TP)50 inline std::time_t toTimeT(TimePoint<> TP) {
51   using namespace std::chrono;
52   return system_clock::to_time_t(
53       time_point_cast<system_clock::time_point::duration>(TP));
54 }
55 
56 /// Convert a UtcTime to std::time_t
toTimeT(UtcTime<> TP)57 inline std::time_t toTimeT(UtcTime<> TP) {
58   using namespace std::chrono;
59   return system_clock::to_time_t(time_point<system_clock, seconds>(
60       duration_cast<seconds>(TP.time_since_epoch())));
61 }
62 
63 /// Convert a std::time_t to a TimePoint
64 inline TimePoint<std::chrono::seconds>
toTimePoint(std::time_t T)65 toTimePoint(std::time_t T) {
66   using namespace std::chrono;
67   return time_point_cast<seconds>(system_clock::from_time_t(T));
68 }
69 
70 /// Convert a std::time_t + nanoseconds to a TimePoint
71 inline TimePoint<>
toTimePoint(std::time_t T,uint32_t nsec)72 toTimePoint(std::time_t T, uint32_t nsec) {
73   using namespace std::chrono;
74   return time_point_cast<nanoseconds>(system_clock::from_time_t(T))
75     + nanoseconds(nsec);
76 }
77 
78 } // namespace sys
79 
80 LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, sys::TimePoint<> TP);
81 LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, sys::UtcTime<> TP);
82 
83 /// Format provider for TimePoint<>
84 ///
85 /// The options string is a strftime format string, with extensions:
86 ///   - %L is millis: 000-999
87 ///   - %f is micros: 000000-999999
88 ///   - %N is nanos: 000000000 - 999999999
89 ///
90 /// If no options are given, the default format is "%Y-%m-%d %H:%M:%S.%N".
91 template <>
92 struct format_provider<sys::TimePoint<>> {
93   LLVM_ABI static void format(const sys::TimePoint<> &TP, llvm::raw_ostream &OS,
94                               StringRef Style);
95 };
96 
97 template <> struct format_provider<sys::UtcTime<std::chrono::seconds>> {
98   LLVM_ABI static void format(const sys::UtcTime<std::chrono::seconds> &TP,
99                               llvm::raw_ostream &OS, StringRef Style);
100 };
101 
102 namespace detail {
103 template <typename Period> struct unit { static const char value[]; };
104 template <typename Period> const char unit<Period>::value[] = "";
105 
106 template <> struct unit<std::ratio<3600>> {
107   LLVM_ABI static const char value[];
108 };
109 template <> struct unit<std::ratio<60>> {
110   LLVM_ABI static const char value[];
111 };
112 template <> struct unit<std::ratio<1>> {
113   LLVM_ABI static const char value[];
114 };
115 template <> struct unit<std::milli> {
116   LLVM_ABI static const char value[];
117 };
118 template <> struct unit<std::micro> {
119   LLVM_ABI static const char value[];
120 };
121 template <> struct unit<std::nano> {
122   LLVM_ABI static const char value[];
123 };
124 } // namespace detail
125 
126 /// Implementation of format_provider<T> for duration types.
127 ///
128 /// The options string of a duration type has the grammar:
129 ///
130 ///   duration_options  ::= [unit][show_unit [number_options]]
131 ///   unit              ::= `h`|`m`|`s`|`ms|`us`|`ns`
132 ///   show_unit         ::= `+` | `-`
133 ///   number_options    ::= options string for a integral or floating point type
134 ///
135 ///   Examples
136 ///   =================================
137 ///   |  options  | Input | Output    |
138 ///   =================================
139 ///   | ""        | 1s    | 1 s       |
140 ///   | "ms"      | 1s    | 1000 ms   |
141 ///   | "ms-"     | 1s    | 1000      |
142 ///   | "ms-n"    | 1s    | 1,000     |
143 ///   | ""        | 1.0s  | 1.00 s    |
144 ///   =================================
145 ///
146 ///  If the unit of the duration type is not one of the units specified above,
147 ///  it is still possible to format it, provided you explicitly request a
148 ///  display unit or you request that the unit is not displayed.
149 
150 template <typename Rep, typename Period>
151 struct format_provider<std::chrono::duration<Rep, Period>> {
152 private:
153   typedef std::chrono::duration<Rep, Period> Dur;
154   typedef std::conditional_t<std::chrono::treat_as_floating_point<Rep>::value,
155                              double, intmax_t>
156       InternalRep;
157 
158   template <typename AsPeriod> static InternalRep getAs(const Dur &D) {
159     using namespace std::chrono;
160     return duration_cast<duration<InternalRep, AsPeriod>>(D).count();
161   }
162 
163   static std::pair<InternalRep, StringRef> consumeUnit(StringRef &Style,
164                                                         const Dur &D) {
165     using namespace std::chrono;
166     if (Style.consume_front("ns"))
167       return {getAs<std::nano>(D), "ns"};
168     if (Style.consume_front("us"))
169       return {getAs<std::micro>(D), "us"};
170     if (Style.consume_front("ms"))
171       return {getAs<std::milli>(D), "ms"};
172     if (Style.consume_front("s"))
173       return {getAs<std::ratio<1>>(D), "s"};
174     if (Style.consume_front("m"))
175       return {getAs<std::ratio<60>>(D), "m"};
176     if (Style.consume_front("h"))
177       return {getAs<std::ratio<3600>>(D), "h"};
178     return {D.count(), detail::unit<Period>::value};
179   }
180 
181   static bool consumeShowUnit(StringRef &Style) {
182     if (Style.empty())
183       return true;
184     if (Style.consume_front("-"))
185       return false;
186     if (Style.consume_front("+"))
187       return true;
188     assert(0 && "Unrecognised duration format");
189     return true;
190   }
191 
192 public:
193   static void format(const Dur &D, llvm::raw_ostream &Stream, StringRef Style) {
194     InternalRep count;
195     StringRef unit;
196     std::tie(count, unit) = consumeUnit(Style, D);
197     bool show_unit = consumeShowUnit(Style);
198 
199     format_provider<InternalRep>::format(count, Stream, Style);
200 
201     if (show_unit) {
202       assert(!unit.empty());
203       Stream << " " << unit;
204     }
205   }
206 };
207 
208 } // namespace llvm
209 
210 #endif // LLVM_SUPPORT_CHRONO_H
211