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/atomicops.h"
9#include "base/logging.h"
10#include "base/metrics/histogram.h"
11#include "base/time/time.h"
12
13//------------------------------------------------------------------------------
14// Histograms are often put in areas where they are called many many times, and
15// performance is critical.  As a result, they are designed to have a very low
16// recurring cost of executing (adding additional samples).  Toward that end,
17// the macros declare a static pointer to the histogram in question, and only
18// take a "slow path" to construct (or find) the histogram on the first run
19// through the macro.  We leak the histograms at shutdown time so that we don't
20// have to validate using the pointers at any time during the running of the
21// process.
22
23// The following code is generally what a thread-safe static pointer
24// initialization looks like for a histogram (after a macro is expanded).  This
25// sample is an expansion (with comments) of the code for
26// LOCAL_HISTOGRAM_CUSTOM_COUNTS().
27
28/*
29  do {
30    // The pointer's presence indicates the initialization is complete.
31    // Initialization is idempotent, so it can safely be atomically repeated.
32    static base::subtle::AtomicWord atomic_histogram_pointer = 0;
33
34    // Acquire_Load() ensures that we acquire visibility to the pointed-to data
35    // in the histogram.
36    base::Histogram* histogram_pointer(reinterpret_cast<base::Histogram*>(
37        base::subtle::Acquire_Load(&atomic_histogram_pointer)));
38
39    if (!histogram_pointer) {
40      // This is the slow path, which will construct OR find the matching
41      // histogram.  FactoryGet includes locks on a global histogram name map
42      // and is completely thread safe.
43      histogram_pointer = base::Histogram::FactoryGet(
44          name, min, max, bucket_count, base::HistogramBase::kNoFlags);
45
46      // Use Release_Store to ensure that the histogram data is made available
47      // globally before we make the pointer visible.
48      // Several threads may perform this store, but the same value will be
49      // stored in all cases (for a given named/spec'ed histogram).
50      // We could do this without any barrier, since FactoryGet entered and
51      // exited a lock after construction, but this barrier makes things clear.
52      base::subtle::Release_Store(&atomic_histogram_pointer,
53          reinterpret_cast<base::subtle::AtomicWord>(histogram_pointer));
54    }
55
56    // Ensure calling contract is upheld, and the name does NOT vary.
57    DCHECK(histogram_pointer->histogram_name() == constant_histogram_name);
58
59    histogram_pointer->Add(sample);
60  } while (0);
61*/
62
63// The above pattern is repeated in several macros.  The only elements that
64// vary are the invocation of the Add(sample) vs AddTime(sample), and the choice
65// of which FactoryGet method to use.  The different FactoryGet methods have
66// various argument lists, so the function with its argument list is provided as
67// a macro argument here.  The name is only used in a DCHECK, to assure that
68// callers don't try to vary the name of the histogram (which would tend to be
69// ignored by the one-time initialization of the histogtram_pointer).
70#define STATIC_HISTOGRAM_POINTER_BLOCK(constant_histogram_name,           \
71                                       histogram_add_method_invocation,   \
72                                       histogram_factory_get_invocation)  \
73  do {                                                                    \
74    static base::subtle::AtomicWord atomic_histogram_pointer = 0;         \
75    base::HistogramBase* histogram_pointer(                               \
76        reinterpret_cast<base::HistogramBase*>(                           \
77            base::subtle::Acquire_Load(&atomic_histogram_pointer)));      \
78    if (!histogram_pointer) {                                             \
79      histogram_pointer = histogram_factory_get_invocation;               \
80      base::subtle::Release_Store(                                        \
81          &atomic_histogram_pointer,                                      \
82          reinterpret_cast<base::subtle::AtomicWord>(histogram_pointer)); \
83    }                                                                     \
84    if (DCHECK_IS_ON())                                                   \
85      histogram_pointer->CheckName(constant_histogram_name);              \
86    histogram_pointer->histogram_add_method_invocation;                   \
87  } while (0)
88
89//------------------------------------------------------------------------------
90// Provide easy general purpose histogram in a macro, just like stats counters.
91// The first four macros use 50 buckets.
92
93#define LOCAL_HISTOGRAM_TIMES(name, sample) LOCAL_HISTOGRAM_CUSTOM_TIMES( \
94    name, sample, base::TimeDelta::FromMilliseconds(1), \
95    base::TimeDelta::FromSeconds(10), 50)
96
97// For folks that need real specific times, use this to select a precise range
98// of times you want plotted, and the number of buckets you want used.
99#define LOCAL_HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) \
100    STATIC_HISTOGRAM_POINTER_BLOCK(name, AddTime(sample), \
101        base::Histogram::FactoryTimeGet(name, min, max, bucket_count, \
102                                        base::HistogramBase::kNoFlags))
103
104#define LOCAL_HISTOGRAM_COUNTS(name, sample) LOCAL_HISTOGRAM_CUSTOM_COUNTS( \
105    name, sample, 1, 1000000, 50)
106
107#define LOCAL_HISTOGRAM_COUNTS_100(name, sample) \
108    LOCAL_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1, 100, 50)
109
110#define LOCAL_HISTOGRAM_COUNTS_10000(name, sample) \
111    LOCAL_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1, 10000, 50)
112
113#define LOCAL_HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) \
114    STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample), \
115        base::Histogram::FactoryGet(name, min, max, bucket_count, \
116                                    base::HistogramBase::kNoFlags))
117
118// This is a helper macro used by other macros and shouldn't be used directly.
119#define HISTOGRAM_ENUMERATION_WITH_FLAG(name, sample, boundary, flag) \
120    STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample), \
121        base::LinearHistogram::FactoryGet(name, 1, boundary, boundary + 1, \
122            flag))
123
124#define LOCAL_HISTOGRAM_PERCENTAGE(name, under_one_hundred) \
125    LOCAL_HISTOGRAM_ENUMERATION(name, under_one_hundred, 101)
126
127#define LOCAL_HISTOGRAM_BOOLEAN(name, sample) \
128    STATIC_HISTOGRAM_POINTER_BLOCK(name, AddBoolean(sample), \
129        base::BooleanHistogram::FactoryGet(name, base::Histogram::kNoFlags))
130
131// Support histograming of an enumerated value.  The samples should always be
132// strictly less than |boundary_value| -- this prevents you from running into
133// problems down the line if you add additional buckets to the histogram.  Note
134// also that, despite explicitly setting the minimum bucket value to |1| below,
135// it is fine for enumerated histograms to be 0-indexed -- this is because
136// enumerated histograms should never have underflow.
137#define LOCAL_HISTOGRAM_ENUMERATION(name, sample, boundary_value) \
138    STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample), \
139        base::LinearHistogram::FactoryGet(name, 1, boundary_value, \
140            boundary_value + 1, base::HistogramBase::kNoFlags))
141
142// Support histograming of an enumerated value. Samples should be one of the
143// std::vector<int> list provided via |custom_ranges|. See comments above
144// CustomRanges::FactoryGet about the requirement of |custom_ranges|.
145// You can use the helper function CustomHistogram::ArrayToCustomRanges to
146// transform a C-style array of valid sample values to a std::vector<int>.
147#define LOCAL_HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) \
148    STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample), \
149        base::CustomHistogram::FactoryGet(name, custom_ranges, \
150                                          base::HistogramBase::kNoFlags))
151
152#define LOCAL_HISTOGRAM_MEMORY_KB(name, sample) LOCAL_HISTOGRAM_CUSTOM_COUNTS( \
153    name, sample, 1000, 500000, 50)
154
155//------------------------------------------------------------------------------
156// The following macros provide typical usage scenarios for callers that wish
157// to record histogram data, and have the data submitted/uploaded via UMA.
158// Not all systems support such UMA, but if they do, the following macros
159// should work with the service.
160
161#define UMA_HISTOGRAM_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
162    name, sample, base::TimeDelta::FromMilliseconds(1), \
163    base::TimeDelta::FromSeconds(10), 50)
164
165#define UMA_HISTOGRAM_MEDIUM_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
166    name, sample, base::TimeDelta::FromMilliseconds(10), \
167    base::TimeDelta::FromMinutes(3), 50)
168
169// Use this macro when times can routinely be much longer than 10 seconds.
170#define UMA_HISTOGRAM_LONG_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
171    name, sample, base::TimeDelta::FromMilliseconds(1), \
172    base::TimeDelta::FromHours(1), 50)
173
174// Use this macro when times can routinely be much longer than 10 seconds and
175// you want 100 buckets.
176#define UMA_HISTOGRAM_LONG_TIMES_100(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
177    name, sample, base::TimeDelta::FromMilliseconds(1), \
178    base::TimeDelta::FromHours(1), 100)
179
180#define UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) \
181    STATIC_HISTOGRAM_POINTER_BLOCK(name, AddTime(sample), \
182        base::Histogram::FactoryTimeGet(name, min, max, bucket_count, \
183            base::HistogramBase::kUmaTargetedHistogramFlag))
184
185#define UMA_HISTOGRAM_COUNTS(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
186    name, sample, 1, 1000000, 50)
187
188#define UMA_HISTOGRAM_COUNTS_100(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
189    name, sample, 1, 100, 50)
190
191#define UMA_HISTOGRAM_COUNTS_1000(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
192    name, sample, 1, 1000, 50)
193
194#define UMA_HISTOGRAM_COUNTS_10000(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
195    name, sample, 1, 10000, 50)
196
197#define UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) \
198    STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample), \
199        base::Histogram::FactoryGet(name, min, max, bucket_count, \
200            base::HistogramBase::kUmaTargetedHistogramFlag))
201
202#define UMA_HISTOGRAM_MEMORY_KB(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
203    name, sample, 1000, 500000, 50)
204
205#define UMA_HISTOGRAM_MEMORY_MB(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
206    name, sample, 1, 1000, 50)
207
208#define UMA_HISTOGRAM_MEMORY_LARGE_MB(name, sample) \
209    UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 1, 64000, 100)
210
211#define UMA_HISTOGRAM_PERCENTAGE(name, under_one_hundred) \
212    UMA_HISTOGRAM_ENUMERATION(name, under_one_hundred, 101)
213
214#define UMA_HISTOGRAM_BOOLEAN(name, sample) \
215    STATIC_HISTOGRAM_POINTER_BLOCK(name, AddBoolean(sample), \
216        base::BooleanHistogram::FactoryGet(name, \
217            base::HistogramBase::kUmaTargetedHistogramFlag))
218
219// The samples should always be strictly less than |boundary_value|.  For more
220// details, see the comment for the |LOCAL_HISTOGRAM_ENUMERATION| macro, above.
221#define UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value) \
222    HISTOGRAM_ENUMERATION_WITH_FLAG(name, sample, boundary_value, \
223        base::HistogramBase::kUmaTargetedHistogramFlag)
224
225// Similar to UMA_HISTOGRAM_ENUMERATION, but used for recording stability
226// histograms.  Use this if recording a histogram that should be part of the
227// initial stability log.
228#define UMA_STABILITY_HISTOGRAM_ENUMERATION(name, sample, boundary_value) \
229    HISTOGRAM_ENUMERATION_WITH_FLAG(name, sample, boundary_value, \
230        base::HistogramBase::kUmaStabilityHistogramFlag)
231
232#define UMA_HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) \
233    STATIC_HISTOGRAM_POINTER_BLOCK(name, Add(sample), \
234        base::CustomHistogram::FactoryGet(name, custom_ranges, \
235            base::HistogramBase::kUmaTargetedHistogramFlag))
236
237// Scoped class which logs its time on this earth as a UMA statistic. This is
238// recommended for when you want a histogram which measures the time it takes
239// for a method to execute. This measures up to 10 seconds.
240#define SCOPED_UMA_HISTOGRAM_TIMER(name) \
241  SCOPED_UMA_HISTOGRAM_TIMER_EXPANDER(name, false, __COUNTER__)
242
243// Similar scoped histogram timer, but this uses UMA_HISTOGRAM_LONG_TIMES_100,
244// which measures up to an hour, and uses 100 buckets. This is more expensive
245// to store, so only use if this often takes >10 seconds.
246#define SCOPED_UMA_HISTOGRAM_LONG_TIMER(name) \
247  SCOPED_UMA_HISTOGRAM_TIMER_EXPANDER(name, true, __COUNTER__)
248
249// This nested macro is necessary to expand __COUNTER__ to an actual value.
250#define SCOPED_UMA_HISTOGRAM_TIMER_EXPANDER(name, is_long, key) \
251  SCOPED_UMA_HISTOGRAM_TIMER_UNIQUE(name, is_long, key)
252
253#define SCOPED_UMA_HISTOGRAM_TIMER_UNIQUE(name, is_long, key) \
254  class ScopedHistogramTimer##key { \
255   public: \
256    ScopedHistogramTimer##key() : constructed_(base::TimeTicks::Now()) {} \
257    ~ScopedHistogramTimer##key() { \
258      base::TimeDelta elapsed = base::TimeTicks::Now() - constructed_; \
259      if (is_long) { \
260        UMA_HISTOGRAM_LONG_TIMES_100(name, elapsed); \
261      } else { \
262        UMA_HISTOGRAM_TIMES(name, elapsed); \
263      } \
264    } \
265   private: \
266    base::TimeTicks constructed_; \
267  } scoped_histogram_timer_##key
268
269#endif  // BASE_METRICS_HISTOGRAM_MACROS_H_
270