• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_METRICS_HISTOGRAM_MACROS_H_
6 #define BASE_METRICS_HISTOGRAM_MACROS_H_
7 
8 #include "base/macros.h"
9 #include "base/metrics/histogram.h"
10 #include "base/metrics/histogram_macros_internal.h"
11 #include "base/metrics/histogram_macros_local.h"
12 #include "base/time/time.h"
13 
14 
15 // Macros for efficient use of histograms.
16 //
17 // For best practices on deciding when to emit to a histogram and what form
18 // the histogram should take, see
19 // https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/metrics/histograms/README.md
20 
21 // TODO(rkaplow): Link to proper documentation on metric creation once we have
22 // it in a good state.
23 
24 // All of these macros must be called with |name| as a runtime constant - it
25 // doesn't have to literally be a constant, but it must be the same string on
26 // all calls from a particular call site. If this rule is violated, it is
27 // possible the data will be written to the wrong histogram.
28 
29 //------------------------------------------------------------------------------
30 // Enumeration histograms.
31 
32 // These macros create histograms for enumerated data. Ideally, the data should
33 // be of the form of "event occurs, log the result". We recommended not putting
34 // related but not directly connected data as enums within the same histogram.
35 // You should be defining an associated Enum, and the input sample should be
36 // an element of the Enum.
37 // All of these macros must be called with |name| as a runtime constant.
38 
39 // The first variant of UMA_HISTOGRAM_ENUMERATION accepts two arguments: the
40 // histogram name and the enum sample. It deduces the correct boundary value to
41 // use by looking for an enumerator with the name kMaxValue. kMaxValue should
42 // share the value of the highest enumerator: this avoids switch statements
43 // having to handle a sentinel no-op value.
44 //
45 // Sample usage:
46 //   // These values are persisted to logs. Entries should not be renumbered and
47 //   // numeric values should never be reused.
48 //   enum class MyEnum {
49 //     kFirstValue = 0,
50 //     kSecondValue = 1,
51 //     ...
52 //     kFinalValue = N,
53 //     kMaxValue = kFinalValue,
54 //   };
55 //   UMA_HISTOGRAM_ENUMERATION("My.Enumeration", MyEnum::kSomeValue);
56 //
57 // The second variant requires three arguments: the first two are the same as
58 // before, and the third argument is the enum boundary: this must be strictly
59 // greater than any other enumerator that will be sampled.
60 //
61 // Sample usage:
62 //   // These values are persisted to logs. Entries should not be renumbered and
63 //   // numeric values should never be reused.
64 //   enum class MyEnum {
65 //     FIRST_VALUE = 0,
66 //     SECOND_VALUE = 1,
67 //     ...
68 //     FINAL_VALUE = N,
69 //     COUNT
70 //   };
71 //   UMA_HISTOGRAM_ENUMERATION("My.Enumeration",
72 //                             MyEnum::SOME_VALUE, MyEnum::COUNT);
73 //
74 // Note: If the enum is used in a switch, it is often desirable to avoid writing
75 // a case statement to handle an unused sentinel value (i.e. COUNT in the above
76 // example). For scoped enums, this is awkward since it requires casting the
77 // enum to an arithmetic type and adding one. Instead, prefer the two argument
78 // version of the macro which automatically deduces the boundary from kMaxValue.
79 #define UMA_HISTOGRAM_ENUMERATION(name, ...)                            \
80   CR_EXPAND_ARG(INTERNAL_UMA_HISTOGRAM_ENUMERATION_GET_MACRO(           \
81       __VA_ARGS__, INTERNAL_UMA_HISTOGRAM_ENUMERATION_SPECIFY_BOUNDARY, \
82       INTERNAL_UMA_HISTOGRAM_ENUMERATION_DEDUCE_BOUNDARY)(              \
83       name, __VA_ARGS__, base::HistogramBase::kUmaTargetedHistogramFlag))
84 
85 // As above but "scaled" count to avoid overflows caused by increments of
86 // large amounts. See UMA_HISTOGRAM_SCALED_EXACT_LINEAR for more information.
87 // Only the new format utilizing an internal kMaxValue is supported.
88 // It'll be necessary to #include "base/lazy_instance.h" to use this macro.
89 #define UMA_HISTOGRAM_SCALED_ENUMERATION(name, sample, count, scale) \
90   INTERNAL_HISTOGRAM_SCALED_ENUMERATION_WITH_FLAG(                   \
91       name, sample, count, scale,                                    \
92       base::HistogramBase::kUmaTargetedHistogramFlag)
93 
94 // Histogram for boolean values.
95 
96 // Sample usage:
97 //   UMA_HISTOGRAM_BOOLEAN("Histogram.Boolean", bool);
98 #define UMA_HISTOGRAM_BOOLEAN(name, sample)                                    \
99     STATIC_HISTOGRAM_POINTER_BLOCK(name, AddBoolean(sample),                   \
100         base::BooleanHistogram::FactoryGet(name,                               \
101             base::HistogramBase::kUmaTargetedHistogramFlag))
102 
103 //------------------------------------------------------------------------------
104 // Linear histograms.
105 
106 // All of these macros must be called with |name| as a runtime constant.
107 
108 // Used for capturing integer data with a linear bucketing scheme. This can be
109 // used when you want the exact value of some small numeric count, with a max of
110 // 100 or less. If you need to capture a range of greater than 100, we recommend
111 // the use of the COUNT histograms below.
112 
113 // Sample usage:
114 //   UMA_HISTOGRAM_EXACT_LINEAR("Histogram.Linear", count, 10);
115 #define UMA_HISTOGRAM_EXACT_LINEAR(name, sample, value_max) \
116   INTERNAL_HISTOGRAM_EXACT_LINEAR_WITH_FLAG(                \
117       name, sample, value_max, base::HistogramBase::kUmaTargetedHistogramFlag)
118 
119 // Used for capturing basic percentages. This will be 100 buckets of size 1.
120 
121 // Sample usage:
122 //   UMA_HISTOGRAM_PERCENTAGE("Histogram.Percent", percent_as_int);
123 #define UMA_HISTOGRAM_PERCENTAGE(name, percent_as_int) \
124   UMA_HISTOGRAM_EXACT_LINEAR(name, percent_as_int, 101)
125 
126 //------------------------------------------------------------------------------
127 // Scaled Linear histograms.
128 
129 // These take |count| and |scale| parameters to allow cumulative reporting of
130 // large numbers. Only the scaled count is reported but the reminder is kept so
131 // multiple calls will accumulate correctly.  Only "exact linear" is supported.
132 // It'll be necessary to #include "base/lazy_instance.h" to use this macro.
133 
134 #define UMA_HISTOGRAM_SCALED_EXACT_LINEAR(name, sample, count, value_max, \
135                                           scale)                          \
136   INTERNAL_HISTOGRAM_SCALED_EXACT_LINEAR_WITH_FLAG(                       \
137       name, sample, count, value_max, scale,                              \
138       base::HistogramBase::kUmaTargetedHistogramFlag)
139 
140 //------------------------------------------------------------------------------
141 // Count histograms. These are used for collecting numeric data. Note that we
142 // have macros for more specialized use cases below (memory, time, percentages).
143 
144 // The number suffixes here refer to the max size of the sample, i.e. COUNT_1000
145 // will be able to collect samples of counts up to 1000. The default number of
146 // buckets in all default macros is 50. We recommend erring on the side of too
147 // large a range versus too short a range.
148 // These macros default to exponential histograms - i.e. the lengths of the
149 // bucket ranges exponentially increase as the sample range increases.
150 // These should *not* be used if you are interested in exact counts, i.e. a
151 // bucket range of 1. In these cases, you should use the ENUMERATION macros
152 // defined later. These should also not be used to capture the number of some
153 // event, i.e. "button X was clicked N times". In this cases, an enum should be
154 // used, ideally with an appropriate baseline enum entry included.
155 // All of these macros must be called with |name| as a runtime constant.
156 
157 // Sample usage:
158 //   UMA_HISTOGRAM_COUNTS_1M("My.Histogram", sample);
159 
160 #define UMA_HISTOGRAM_COUNTS_100(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS(    \
161     name, sample, 1, 100, 50)
162 
163 #define UMA_HISTOGRAM_COUNTS_1000(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS(   \
164     name, sample, 1, 1000, 50)
165 
166 #define UMA_HISTOGRAM_COUNTS_10000(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS(  \
167     name, sample, 1, 10000, 50)
168 
169 #define UMA_HISTOGRAM_COUNTS_100000(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
170     name, sample, 1, 100000, 50)
171 
172 #define UMA_HISTOGRAM_COUNTS_1M(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS(     \
173     name, sample, 1, 1000000, 50)
174 
175 #define UMA_HISTOGRAM_COUNTS_10M(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS(    \
176     name, sample, 1, 10000000, 50)
177 
178 // This can be used when the default ranges are not sufficient. This macro lets
179 // the metric developer customize the min and max of the sampled range, as well
180 // as the number of buckets recorded.
181 // Any data outside the range here will be put in underflow and overflow
182 // buckets. Min values should be >=1 as emitted 0s will still go into the
183 // underflow bucket.
184 
185 // Sample usage:
186 //   UMA_HISTOGRAM_CUSTOM_COUNTS("My.Histogram", 1, 100000000, 100);
187 #define UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count)      \
188     INTERNAL_HISTOGRAM_CUSTOM_COUNTS_WITH_FLAG(                                \
189         name, sample, min, max, bucket_count,                                  \
190         base::HistogramBase::kUmaTargetedHistogramFlag)
191 
192 //------------------------------------------------------------------------------
193 // Timing histograms. These are used for collecting timing data (generally
194 // latencies).
195 
196 // These macros create exponentially sized histograms (lengths of the bucket
197 // ranges exponentially increase as the sample range increases). The input
198 // sample is a base::TimeDelta. The output data is measured in ms granularity.
199 // All of these macros must be called with |name| as a runtime constant.
200 
201 // Sample usage:
202 //   UMA_HISTOGRAM_TIMES("My.Timing.Histogram", time_delta);
203 
204 // Short timings - up to 10 seconds. For high-resolution (microseconds) timings,
205 // see UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES.
206 #define UMA_HISTOGRAM_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES(          \
207     name, sample, base::TimeDelta::FromMilliseconds(1),                        \
208     base::TimeDelta::FromSeconds(10), 50)
209 
210 // Medium timings - up to 3 minutes. Note this starts at 10ms (no good reason,
211 // but not worth changing).
212 #define UMA_HISTOGRAM_MEDIUM_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES(   \
213     name, sample, base::TimeDelta::FromMilliseconds(10),                       \
214     base::TimeDelta::FromMinutes(3), 50)
215 
216 // Long timings - up to an hour.
217 #define UMA_HISTOGRAM_LONG_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES(     \
218     name, sample, base::TimeDelta::FromMilliseconds(1),                        \
219     base::TimeDelta::FromHours(1), 50)
220 
221 // Long timings with higher granularity - up to an hour with 100 buckets.
222 #define UMA_HISTOGRAM_LONG_TIMES_100(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
223     name, sample, base::TimeDelta::FromMilliseconds(1),                        \
224     base::TimeDelta::FromHours(1), 100)
225 
226 // This can be used when the default ranges are not sufficient. This macro lets
227 // the metric developer customize the min and max of the sampled range, as well
228 // as the number of buckets recorded.
229 
230 // Sample usage:
231 //   UMA_HISTOGRAM_CUSTOM_TIMES("Very.Long.Timing.Histogram", time_delta,
232 //       base::TimeDelta::FromSeconds(1), base::TimeDelta::FromDays(1), 100);
233 #define UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) \
234   STATIC_HISTOGRAM_POINTER_BLOCK(                                        \
235       name, AddTimeMillisecondsGranularity(sample),                      \
236       base::Histogram::FactoryTimeGet(                                   \
237           name, min, max, bucket_count,                                  \
238           base::HistogramBase::kUmaTargetedHistogramFlag))
239 
240 // Same as UMA_HISTOGRAM_CUSTOM_TIMES but reports |sample| in microseconds,
241 // dropping the report if this client doesn't have a high-resolution clock.
242 //
243 // Note: dropping reports on clients with low-resolution clocks means these
244 // reports will be biased to a portion of the population on Windows. See
245 // Windows.HasHighResolutionTimeTicks for the affected sample.
246 //
247 // Sample usage:
248 //  UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
249 //      "High.Resolution.TimingMicroseconds.Histogram", time_delta,
250 //      base::TimeDelta::FromMicroseconds(1),
251 //      base::TimeDelta::FromMilliseconds(10), 100);
252 #define UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(name, sample, min, max, \
253                                                 bucket_count)           \
254   STATIC_HISTOGRAM_POINTER_BLOCK(                                       \
255       name, AddTimeMicrosecondsGranularity(sample),                     \
256       base::Histogram::FactoryMicrosecondsTimeGet(                      \
257           name, min, max, bucket_count,                                 \
258           base::HistogramBase::kUmaTargetedHistogramFlag))
259 
260 // Scoped class which logs its time on this earth as a UMA statistic. This is
261 // recommended for when you want a histogram which measures the time it takes
262 // for a method to execute. This measures up to 10 seconds. It uses
263 // UMA_HISTOGRAM_TIMES under the hood.
264 
265 // Sample usage:
266 //   void Function() {
267 //     SCOPED_UMA_HISTOGRAM_TIMER("Component.FunctionTime");
268 //     ...
269 //   }
270 #define SCOPED_UMA_HISTOGRAM_TIMER(name)                                       \
271   INTERNAL_SCOPED_UMA_HISTOGRAM_TIMER_EXPANDER(name, false, __COUNTER__)
272 
273 // Similar scoped histogram timer, but this uses UMA_HISTOGRAM_LONG_TIMES_100,
274 // which measures up to an hour, and uses 100 buckets. This is more expensive
275 // to store, so only use if this often takes >10 seconds.
276 #define SCOPED_UMA_HISTOGRAM_LONG_TIMER(name)                                  \
277   INTERNAL_SCOPED_UMA_HISTOGRAM_TIMER_EXPANDER(name, true, __COUNTER__)
278 
279 
280 //------------------------------------------------------------------------------
281 // Memory histograms.
282 
283 // These macros create exponentially sized histograms (lengths of the bucket
284 // ranges exponentially increase as the sample range increases). The input
285 // sample must be a number measured in kilobytes.
286 // All of these macros must be called with |name| as a runtime constant.
287 
288 // Sample usage:
289 //   UMA_HISTOGRAM_MEMORY_KB("My.Memory.Histogram", memory_in_kb);
290 
291 // Used to measure common KB-granularity memory stats. Range is up to 500000KB -
292 // approximately 500M.
293 #define UMA_HISTOGRAM_MEMORY_KB(name, sample)                                  \
294     UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1000, 500000, 50)
295 
296 // Used to measure common MB-granularity memory stats. Range is up to ~64G.
297 #define UMA_HISTOGRAM_MEMORY_LARGE_MB(name, sample)                            \
298     UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1, 64000, 100)
299 
300 
301 //------------------------------------------------------------------------------
302 // Stability-specific histograms.
303 
304 // Histograms logged in as stability histograms will be included in the initial
305 // stability log. See comments by declaration of
306 // MetricsService::PrepareInitialStabilityLog().
307 // All of these macros must be called with |name| as a runtime constant.
308 
309 // For details on usage, see the documentation on the non-stability equivalents.
310 
311 #define UMA_STABILITY_HISTOGRAM_COUNTS_100(name, sample)                       \
312     UMA_STABILITY_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1, 100, 50)
313 
314 #define UMA_STABILITY_HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max,          \
315                                               bucket_count)                    \
316     INTERNAL_HISTOGRAM_CUSTOM_COUNTS_WITH_FLAG(                                \
317         name, sample, min, max, bucket_count,                                  \
318         base::HistogramBase::kUmaStabilityHistogramFlag)
319 
320 #define UMA_STABILITY_HISTOGRAM_ENUMERATION(name, sample, enum_max)            \
321     INTERNAL_HISTOGRAM_ENUMERATION_WITH_FLAG(                                  \
322         name, sample, enum_max,                                                \
323         base::HistogramBase::kUmaStabilityHistogramFlag)
324 
325 //------------------------------------------------------------------------------
326 // Histogram instantiation helpers.
327 
328 // Support a collection of histograms, perhaps one for each entry in an
329 // enumeration. This macro manages a block of pointers, adding to a specific
330 // one by its index.
331 //
332 // A typical instantiation looks something like this:
333 //  STATIC_HISTOGRAM_POINTER_GROUP(
334 //      GetHistogramNameForIndex(histogram_index),
335 //      histogram_index, MAXIMUM_HISTOGRAM_INDEX, Add(some_delta),
336 //      base::Histogram::FactoryGet(
337 //          GetHistogramNameForIndex(histogram_index),
338 //          MINIMUM_SAMPLE, MAXIMUM_SAMPLE, BUCKET_COUNT,
339 //          base::HistogramBase::kUmaTargetedHistogramFlag));
340 //
341 // Though it seems inefficient to generate the name twice, the first
342 // instance will be used only for DCHECK builds and the second will
343 // execute only during the first access to the given index, after which
344 // the pointer is cached and the name never needed again.
345 #define STATIC_HISTOGRAM_POINTER_GROUP(constant_histogram_name, index,        \
346                                        constant_maximum,                      \
347                                        histogram_add_method_invocation,       \
348                                        histogram_factory_get_invocation)      \
349   do {                                                                        \
350     static base::subtle::AtomicWord atomic_histograms[constant_maximum];      \
351     DCHECK_LE(0, index);                                                      \
352     DCHECK_LT(index, constant_maximum);                                       \
353     HISTOGRAM_POINTER_USE(&atomic_histograms[index], constant_histogram_name, \
354                           histogram_add_method_invocation,                    \
355                           histogram_factory_get_invocation);                  \
356   } while (0)
357 
358 //------------------------------------------------------------------------------
359 // Deprecated histogram macros. Not recommended for current use.
360 
361 // Legacy name for UMA_HISTOGRAM_COUNTS_1M. Suggest using explicit naming
362 // and not using this macro going forward.
363 #define UMA_HISTOGRAM_COUNTS(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS(        \
364     name, sample, 1, 1000000, 50)
365 
366 // MB-granularity memory metric. This has a short max (1G).
367 #define UMA_HISTOGRAM_MEMORY_MB(name, sample)                                  \
368     UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1, 1000, 50)
369 
370 // For an enum with customized range. In general, sparse histograms should be
371 // used instead.
372 // Samples should be one of the std::vector<int> list provided via
373 // |custom_ranges|. See comments above CustomRanges::FactoryGet about the
374 // requirement of |custom_ranges|. You can use the helper function
375 // CustomHistogram::ArrayToCustomEnumRanges to transform a C-style array of
376 // valid sample values to a std::vector<int>.
377 #define UMA_HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges)          \
378     STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample),                          \
379         base::CustomHistogram::FactoryGet(name, custom_ranges,                 \
380             base::HistogramBase::kUmaTargetedHistogramFlag))
381 
382 #endif  // BASE_METRICS_HISTOGRAM_MACROS_H_
383