histogram.h revision 3f50c38dc070f4bb515c1b64450dae14f316474e
1// Copyright (c) 2011 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// Histogram is an object that aggregates statistics, and can summarize them in
6// various forms, including ASCII graphical, HTML, and numerically (as a
7// vector of numbers corresponding to each of the aggregating buckets).
8
9// It supports calls to accumulate either time intervals (which are processed
10// as integral number of milliseconds), or arbitrary integral units.
11
12// The default layout of buckets is exponential.  For example, buckets might
13// contain (sequentially) the count of values in the following intervals:
14// [0,1), [1,2), [2,4), [4,8), [8,16), [16,32), [32,64), [64,infinity)
15// That bucket allocation would actually result from construction of a histogram
16// for values between 1 and 64, with 8 buckets, such as:
17// Histogram count(L"some name", 1, 64, 8);
18// Note that the underflow bucket [0,1) and the overflow bucket [64,infinity)
19// are not counted by the constructor in the user supplied "bucket_count"
20// argument.
21// The above example has an exponential ratio of 2 (doubling the bucket width
22// in each consecutive bucket.  The Histogram class automatically calculates
23// the smallest ratio that it can use to construct the number of buckets
24// selected in the constructor.  An another example, if you had 50 buckets,
25// and millisecond time values from 1 to 10000, then the ratio between
26// consecutive bucket widths will be approximately somewhere around the 50th
27// root of 10000.  This approach provides very fine grain (narrow) buckets
28// at the low end of the histogram scale, but allows the histogram to cover a
29// gigantic range with the addition of very few buckets.
30
31#ifndef BASE_METRICS_HISTOGRAM_H_
32#define BASE_METRICS_HISTOGRAM_H_
33#pragma once
34
35#include <map>
36#include <string>
37#include <vector>
38
39#include "base/gtest_prod_util.h"
40#include "base/ref_counted.h"
41#include "base/logging.h"
42#include "base/time.h"
43
44class Pickle;
45
46namespace base {
47
48class Lock;
49
50//------------------------------------------------------------------------------
51// Provide easy general purpose histogram in a macro, just like stats counters.
52// The first four macros use 50 buckets.
53
54#define HISTOGRAM_TIMES(name, sample) HISTOGRAM_CUSTOM_TIMES( \
55    name, sample, base::TimeDelta::FromMilliseconds(1), \
56    base::TimeDelta::FromSeconds(10), 50)
57
58#define HISTOGRAM_COUNTS(name, sample) HISTOGRAM_CUSTOM_COUNTS( \
59    name, sample, 1, 1000000, 50)
60
61#define HISTOGRAM_COUNTS_100(name, sample) HISTOGRAM_CUSTOM_COUNTS( \
62    name, sample, 1, 100, 50)
63
64#define HISTOGRAM_COUNTS_10000(name, sample) HISTOGRAM_CUSTOM_COUNTS( \
65    name, sample, 1, 10000, 50)
66
67#define HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) do { \
68    static scoped_refptr<base::Histogram> counter = \
69        base::Histogram::FactoryGet(name, min, max, bucket_count, \
70                                    base::Histogram::kNoFlags); \
71    DCHECK_EQ(name, counter->histogram_name()); \
72    if (counter.get()) counter->Add(sample); \
73  } while (0)
74
75#define HISTOGRAM_PERCENTAGE(name, under_one_hundred) \
76    HISTOGRAM_ENUMERATION(name, under_one_hundred, 101)
77
78// For folks that need real specific times, use this to select a precise range
79// of times you want plotted, and the number of buckets you want used.
80#define HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) do { \
81    static scoped_refptr<base::Histogram> counter = \
82        base::Histogram::FactoryTimeGet(name, min, max, bucket_count, \
83                                        base::Histogram::kNoFlags); \
84    DCHECK_EQ(name, counter->histogram_name()); \
85    if (counter.get()) counter->AddTime(sample); \
86  } while (0)
87
88// DO NOT USE THIS.  It is being phased out, in favor of HISTOGRAM_CUSTOM_TIMES.
89#define HISTOGRAM_CLIPPED_TIMES(name, sample, min, max, bucket_count) do { \
90    static scoped_refptr<base::Histogram> counter = \
91        base::Histogram::FactoryTimeGet(name, min, max, bucket_count, \
92                                        base::Histogram::kNoFlags); \
93    DCHECK_EQ(name, counter->histogram_name()); \
94    if ((sample) < (max) && counter.get()) counter->AddTime(sample); \
95  } while (0)
96
97// Support histograming of an enumerated value.  The samples should always be
98// less than boundary_value.
99
100#define HISTOGRAM_ENUMERATION(name, sample, boundary_value) do { \
101    static scoped_refptr<base::Histogram> counter = \
102        base::LinearHistogram::FactoryGet(name, 1, boundary_value, \
103                                          boundary_value + 1, \
104                                          base::Histogram::kNoFlags); \
105    DCHECK_EQ(name, counter->histogram_name()); \
106    if (counter.get()) counter->Add(sample); \
107  } while (0)
108
109#define HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) do { \
110    static scoped_refptr<base::Histogram> counter = \
111        base::CustomHistogram::FactoryGet(name, custom_ranges, \
112                                          base::Histogram::kNoFlags); \
113    DCHECK_EQ(name, counter->histogram_name()); \
114    if (counter.get()) counter->Add(sample); \
115  } while (0)
116
117
118//------------------------------------------------------------------------------
119// Define Debug vs non-debug flavors of macros.
120#ifndef NDEBUG
121
122#define DHISTOGRAM_TIMES(name, sample) HISTOGRAM_TIMES(name, sample)
123#define DHISTOGRAM_COUNTS(name, sample) HISTOGRAM_COUNTS(name, sample)
124#define DHISTOGRAM_PERCENTAGE(name, under_one_hundred) HISTOGRAM_PERCENTAGE(\
125    name, under_one_hundred)
126#define DHISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) \
127    HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count)
128#define DHISTOGRAM_CLIPPED_TIMES(name, sample, min, max, bucket_count) \
129    HISTOGRAM_CLIPPED_TIMES(name, sample, min, max, bucket_count)
130#define DHISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) \
131    HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count)
132#define DHISTOGRAM_ENUMERATION(name, sample, boundary_value) \
133    HISTOGRAM_ENUMERATION(name, sample, boundary_value)
134#define DHISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) \
135    HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges)
136
137#else  // NDEBUG
138
139#define DHISTOGRAM_TIMES(name, sample) do {} while (0)
140#define DHISTOGRAM_COUNTS(name, sample) do {} while (0)
141#define DHISTOGRAM_PERCENTAGE(name, under_one_hundred) do {} while (0)
142#define DHISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) \
143    do {} while (0)
144#define DHISTOGRAM_CLIPPED_TIMES(name, sample, min, max, bucket_count) \
145    do {} while (0)
146#define DHISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) \
147    do {} while (0)
148#define DHISTOGRAM_ENUMERATION(name, sample, boundary_value) do {} while (0)
149#define DHISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) \
150    do {} while (0)
151
152#endif  // NDEBUG
153
154//------------------------------------------------------------------------------
155// The following macros provide typical usage scenarios for callers that wish
156// to record histogram data, and have the data submitted/uploaded via UMA.
157// Not all systems support such UMA, but if they do, the following macros
158// should work with the service.
159
160#define UMA_HISTOGRAM_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
161    name, sample, base::TimeDelta::FromMilliseconds(1), \
162    base::TimeDelta::FromSeconds(10), 50)
163
164#define UMA_HISTOGRAM_MEDIUM_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
165    name, sample, base::TimeDelta::FromMilliseconds(10), \
166    base::TimeDelta::FromMinutes(3), 50)
167
168// Use this macro when times can routinely be much longer than 10 seconds.
169#define UMA_HISTOGRAM_LONG_TIMES(name, sample) UMA_HISTOGRAM_CUSTOM_TIMES( \
170    name, sample, base::TimeDelta::FromMilliseconds(1), \
171    base::TimeDelta::FromHours(1), 50)
172
173#define UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) do { \
174    static scoped_refptr<base::Histogram> counter = \
175        base::Histogram::FactoryTimeGet(name, min, max, bucket_count, \
176            base::Histogram::kUmaTargetedHistogramFlag); \
177    DCHECK_EQ(name, counter->histogram_name()); \
178    if (counter.get()) counter->AddTime(sample); \
179  } while (0)
180
181// DO NOT USE THIS.  It is being phased out, in favor of HISTOGRAM_CUSTOM_TIMES.
182#define UMA_HISTOGRAM_CLIPPED_TIMES(name, sample, min, max, bucket_count) do { \
183    static scoped_refptr<base::Histogram> counter = \
184        base::Histogram::FactoryTimeGet(name, min, max, bucket_count, \
185            base::Histogram::kUmaTargetedHistogramFlag); \
186    DCHECK_EQ(name, counter->histogram_name()); \
187    if ((sample) < (max) && counter.get()) counter->AddTime(sample); \
188  } while (0)
189
190#define UMA_HISTOGRAM_COUNTS(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
191    name, sample, 1, 1000000, 50)
192
193#define UMA_HISTOGRAM_COUNTS_100(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
194    name, sample, 1, 100, 50)
195
196#define UMA_HISTOGRAM_COUNTS_10000(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
197    name, sample, 1, 10000, 50)
198
199#define UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) do { \
200    static scoped_refptr<base::Histogram> counter = \
201       base::Histogram::FactoryGet(name, min, max, bucket_count, \
202           base::Histogram::kUmaTargetedHistogramFlag); \
203    DCHECK_EQ(name, counter->histogram_name()); \
204    if (counter.get()) counter->Add(sample); \
205  } while (0)
206
207#define UMA_HISTOGRAM_MEMORY_KB(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
208    name, sample, 1000, 500000, 50)
209
210#define UMA_HISTOGRAM_MEMORY_MB(name, sample) UMA_HISTOGRAM_CUSTOM_COUNTS( \
211    name, sample, 1, 1000, 50)
212
213#define UMA_HISTOGRAM_PERCENTAGE(name, under_one_hundred) \
214    UMA_HISTOGRAM_ENUMERATION(name, under_one_hundred, 101)
215
216#define UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value) do { \
217    static scoped_refptr<base::Histogram> counter = \
218        base::LinearHistogram::FactoryGet(name, 1, boundary_value, \
219            boundary_value + 1, base::Histogram::kUmaTargetedHistogramFlag); \
220    DCHECK_EQ(name, counter->histogram_name()); \
221    if (counter.get()) counter->Add(sample); \
222  } while (0)
223
224#define UMA_HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) do { \
225    static scoped_refptr<base::Histogram> counter = \
226        base::CustomHistogram::FactoryGet(name, custom_ranges, \
227            base::Histogram::kUmaTargetedHistogramFlag); \
228    DCHECK_EQ(name, counter->histogram_name()); \
229    if (counter.get()) counter->Add(sample); \
230  } while (0)
231
232//------------------------------------------------------------------------------
233
234class BooleanHistogram;
235class CustomHistogram;
236class Histogram;
237class LinearHistogram;
238
239class Histogram : public base::RefCountedThreadSafe<Histogram> {
240 public:
241  typedef int Sample;  // Used for samples (and ranges of samples).
242  typedef int Count;  // Used to count samples in a bucket.
243  static const Sample kSampleType_MAX = INT_MAX;
244
245  typedef std::vector<Count> Counts;
246  typedef std::vector<Sample> Ranges;
247
248  // These enums are used to facilitate deserialization of renderer histograms
249  // into the browser.
250  enum ClassType {
251    HISTOGRAM,
252    LINEAR_HISTOGRAM,
253    BOOLEAN_HISTOGRAM,
254    CUSTOM_HISTOGRAM,
255    NOT_VALID_IN_RENDERER
256  };
257
258  enum BucketLayout {
259    EXPONENTIAL,
260    LINEAR,
261    CUSTOM
262  };
263
264  enum Flags {
265    kNoFlags = 0,
266    kUmaTargetedHistogramFlag = 0x1,  // Histogram should be UMA uploaded.
267
268    // Indicate that the histogram was pickled to be sent across an IPC Channel.
269    // If we observe this flag on a histogram being aggregated into after IPC,
270    // then we are running in a single process mode, and the aggregation should
271    // not take place (as we would be aggregating back into the source
272    // histogram!).
273    kIPCSerializationSourceFlag = 0x10,
274
275    kHexRangePrintingFlag = 0x8000,  // Fancy bucket-naming supported.
276  };
277
278  enum Inconsistencies {
279    NO_INCONSISTENCIES = 0x0,
280    RANGE_CHECKSUM_ERROR = 0x1,
281    BUCKET_ORDER_ERROR = 0x2,
282    COUNT_HIGH_ERROR = 0x4,
283    COUNT_LOW_ERROR = 0x8,
284
285    NEVER_EXCEEDED_VALUE = 0x10
286  };
287
288  struct DescriptionPair {
289    Sample sample;
290    const char* description;  // Null means end of a list of pairs.
291  };
292
293  //----------------------------------------------------------------------------
294  // Statistic values, developed over the life of the histogram.
295
296  class SampleSet {
297   public:
298    explicit SampleSet();
299    ~SampleSet();
300
301    // Adjust size of counts_ for use with given histogram.
302    void Resize(const Histogram& histogram);
303    void CheckSize(const Histogram& histogram) const;
304
305    // Accessor for histogram to make routine additions.
306    void Accumulate(Sample value, Count count, size_t index);
307
308    // Accessor methods.
309    Count counts(size_t i) const { return counts_[i]; }
310    Count TotalCount() const;
311    int64 sum() const { return sum_; }
312    int64 square_sum() const { return square_sum_; }
313    int64 redundant_count() const { return redundant_count_; }
314
315    // Arithmetic manipulation of corresponding elements of the set.
316    void Add(const SampleSet& other);
317    void Subtract(const SampleSet& other);
318
319    bool Serialize(Pickle* pickle) const;
320    bool Deserialize(void** iter, const Pickle& pickle);
321
322   protected:
323    // Actual histogram data is stored in buckets, showing the count of values
324    // that fit into each bucket.
325    Counts counts_;
326
327    // Save simple stats locally.  Note that this MIGHT get done in base class
328    // without shared memory at some point.
329    int64 sum_;         // sum of samples.
330    int64 square_sum_;  // sum of squares of samples.
331
332   private:
333    // Allow tests to corrupt our innards for testing purposes.
334    FRIEND_TEST(HistogramTest, CorruptSampleCounts);
335
336    // To help identify memory corruption, we reduntantly save the number of
337    // samples we've accumulated into all of our buckets.  We can compare this
338    // count to the sum of the counts in all buckets, and detect problems.  Note
339    // that due to races in histogram accumulation (if a histogram is indeed
340    // updated on several threads simultaneously), the tallies might mismatch,
341    // and also the snapshotting code may asynchronously get a mismatch (though
342    // generally either race based mismatch cause is VERY rare).
343    int64 redundant_count_;
344  };
345
346  //----------------------------------------------------------------------------
347  // minimum should start from 1. 0 is invalid as a minimum. 0 is an implicit
348  // default underflow bucket.
349  static scoped_refptr<Histogram> FactoryGet(const std::string& name,
350      Sample minimum, Sample maximum, size_t bucket_count, Flags flags);
351  static scoped_refptr<Histogram> FactoryTimeGet(const std::string& name,
352      base::TimeDelta minimum, base::TimeDelta maximum, size_t bucket_count,
353      Flags flags);
354
355  void Add(int value);
356
357  // This method is an interface, used only by BooleanHistogram.
358  virtual void AddBoolean(bool value);
359
360  // Accept a TimeDelta to increment.
361  void AddTime(TimeDelta time) {
362    Add(static_cast<int>(time.InMilliseconds()));
363  }
364
365  void AddSampleSet(const SampleSet& sample);
366
367  // This method is an interface, used only by LinearHistogram.
368  virtual void SetRangeDescriptions(const DescriptionPair descriptions[]);
369
370  // The following methods provide graphical histogram displays.
371  void WriteHTMLGraph(std::string* output) const;
372  void WriteAscii(bool graph_it, const std::string& newline,
373                  std::string* output) const;
374
375  // Support generic flagging of Histograms.
376  // 0x1 Currently used to mark this histogram to be recorded by UMA..
377  // 0x8000 means print ranges in hex.
378  void SetFlags(Flags flags) { flags_ = static_cast<Flags> (flags_ | flags); }
379  void ClearFlags(Flags flags) { flags_ = static_cast<Flags>(flags_ & ~flags); }
380  int flags() const { return flags_; }
381
382  // Convenience methods for serializing/deserializing the histograms.
383  // Histograms from Renderer process are serialized and sent to the browser.
384  // Browser process reconstructs the histogram from the pickled version
385  // accumulates the browser-side shadow copy of histograms (that mirror
386  // histograms created in the renderer).
387
388  // Serialize the given snapshot of a Histogram into a String. Uses
389  // Pickle class to flatten the object.
390  static std::string SerializeHistogramInfo(const Histogram& histogram,
391                                            const SampleSet& snapshot);
392  // The following method accepts a list of pickled histograms and
393  // builds a histogram and updates shadow copy of histogram data in the
394  // browser process.
395  static bool DeserializeHistogramInfo(const std::string& histogram_info);
396
397  // Check to see if bucket ranges, counts and tallies in the snapshot are
398  // consistent with the bucket ranges and checksums in our histogram.  This can
399  // produce a false-alarm if a race occurred in the reading of the data during
400  // a SnapShot process, but should otherwise be false at all times (unless we
401  // have memory over-writes, or DRAM failures).
402  virtual Inconsistencies FindCorruption(const SampleSet& snapshot) const;
403
404  //----------------------------------------------------------------------------
405  // Accessors for factory constuction, serialization and testing.
406  //----------------------------------------------------------------------------
407  virtual ClassType histogram_type() const;
408  const std::string& histogram_name() const { return histogram_name_; }
409  Sample declared_min() const { return declared_min_; }
410  Sample declared_max() const { return declared_max_; }
411  virtual Sample ranges(size_t i) const;
412  Sample range_checksum() const { return range_checksum_; }
413  virtual size_t bucket_count() const;
414  // Snapshot the current complete set of sample data.
415  // Override with atomic/locked snapshot if needed.
416  virtual void SnapshotSample(SampleSet* sample) const;
417
418  virtual bool HasConstructorArguments(Sample minimum, Sample maximum,
419                                       size_t bucket_count);
420
421  virtual bool HasConstructorTimeDeltaArguments(TimeDelta minimum,
422                                                TimeDelta maximum,
423                                                size_t bucket_count);
424
425 protected:
426  friend class base::RefCountedThreadSafe<Histogram>;
427  Histogram(const std::string& name, Sample minimum,
428            Sample maximum, size_t bucket_count);
429  Histogram(const std::string& name, TimeDelta minimum,
430            TimeDelta maximum, size_t bucket_count);
431
432  virtual ~Histogram();
433
434  // Method to override to skip the display of the i'th bucket if it's empty.
435  virtual bool PrintEmptyBucket(size_t index) const;
436
437  //----------------------------------------------------------------------------
438  // Methods to override to create histogram with different bucket widths.
439  //----------------------------------------------------------------------------
440  // Initialize ranges_ mapping.
441  virtual void InitializeBucketRange();
442  // Find bucket to increment for sample value.
443  virtual size_t BucketIndex(Sample value) const;
444  // Get normalized size, relative to the ranges_[i].
445  virtual double GetBucketSize(Count current, size_t i) const;
446
447  // Recalculate range_checksum_.
448  void ResetRangeChecksum();
449
450  // Return a string description of what goes in a given bucket.
451  // Most commonly this is the numeric value, but in derived classes it may
452  // be a name (or string description) given to the bucket.
453  virtual const std::string GetAsciiBucketRange(size_t it) const;
454
455  //----------------------------------------------------------------------------
456  // Methods to override to create thread safe histogram.
457  //----------------------------------------------------------------------------
458  // Update all our internal data, including histogram
459  virtual void Accumulate(Sample value, Count count, size_t index);
460
461  //----------------------------------------------------------------------------
462  // Accessors for derived classes.
463  //----------------------------------------------------------------------------
464  void SetBucketRange(size_t i, Sample value);
465
466  // Validate that ranges_ was created sensibly (top and bottom range
467  // values relate properly to the declared_min_ and declared_max_)..
468  bool ValidateBucketRanges() const;
469
470 private:
471  // Allow tests to corrupt our innards for testing purposes.
472  FRIEND_TEST(HistogramTest, CorruptBucketBounds);
473  FRIEND_TEST(HistogramTest, CorruptSampleCounts);
474
475  // Post constructor initialization.
476  void Initialize();
477
478  // Return true iff the range_checksum_ matches current ranges_ vector.
479  bool HasValidRangeChecksum() const;
480
481  Sample CalculateRangeChecksum() const;
482
483  //----------------------------------------------------------------------------
484  // Helpers for emitting Ascii graphic.  Each method appends data to output.
485
486  // Find out how large the (graphically) the largest bucket will appear to be.
487  double GetPeakBucketSize(const SampleSet& snapshot) const;
488
489  // Write a common header message describing this histogram.
490  void WriteAsciiHeader(const SampleSet& snapshot,
491                        Count sample_count, std::string* output) const;
492
493  // Write information about previous, current, and next buckets.
494  // Information such as cumulative percentage, etc.
495  void WriteAsciiBucketContext(const int64 past, const Count current,
496                               const int64 remaining, const size_t i,
497                               std::string* output) const;
498
499  // Write textual description of the bucket contents (relative to histogram).
500  // Output is the count in the buckets, as well as the percentage.
501  void WriteAsciiBucketValue(Count current, double scaled_sum,
502                             std::string* output) const;
503
504  // Produce actual graph (set of blank vs non blank char's) for a bucket.
505  void WriteAsciiBucketGraph(double current_size, double max_size,
506                             std::string* output) const;
507
508  //----------------------------------------------------------------------------
509  // Invariant values set at/near construction time
510
511  // ASCII version of original name given to the constructor.  All identically
512  // named instances will be coalesced cross-project.
513  const std::string histogram_name_;
514  Sample declared_min_;  // Less than this goes into counts_[0]
515  Sample declared_max_;  // Over this goes into counts_[bucket_count_ - 1].
516  size_t bucket_count_;  // Dimension of counts_[].
517
518  // Flag the histogram for recording by UMA via metric_services.h.
519  Flags flags_;
520
521  // For each index, show the least value that can be stored in the
522  // corresponding bucket. We also append one extra element in this array,
523  // containing kSampleType_MAX, to make calculations easy.
524  // The dimension of ranges_ is bucket_count + 1.
525  Ranges ranges_;
526
527  // For redundancy, we store the sum of all the sample ranges when ranges are
528  // generated.  If ever there is ever a difference, then the histogram must
529  // have been corrupted.
530  Sample range_checksum_;
531
532  // Finally, provide the state that changes with the addition of each new
533  // sample.
534  SampleSet sample_;
535
536  DISALLOW_COPY_AND_ASSIGN(Histogram);
537};
538
539//------------------------------------------------------------------------------
540
541// LinearHistogram is a more traditional histogram, with evenly spaced
542// buckets.
543class LinearHistogram : public Histogram {
544 public:
545  virtual ~LinearHistogram();
546
547  /* minimum should start from 1. 0 is as minimum is invalid. 0 is an implicit
548     default underflow bucket. */
549  static scoped_refptr<Histogram> FactoryGet(const std::string& name,
550      Sample minimum, Sample maximum, size_t bucket_count, Flags flags);
551  static scoped_refptr<Histogram> FactoryTimeGet(const std::string& name,
552      TimeDelta minimum, TimeDelta maximum, size_t bucket_count,
553      Flags flags);
554
555  // Overridden from Histogram:
556  virtual ClassType histogram_type() const;
557
558  // Store a list of number/text values for use in rendering the histogram.
559  // The last element in the array has a null in its "description" slot.
560  virtual void SetRangeDescriptions(const DescriptionPair descriptions[]);
561
562 protected:
563  LinearHistogram(const std::string& name, Sample minimum,
564                  Sample maximum, size_t bucket_count);
565
566  LinearHistogram(const std::string& name, TimeDelta minimum,
567                  TimeDelta maximum, size_t bucket_count);
568
569  // Initialize ranges_ mapping.
570  virtual void InitializeBucketRange();
571  virtual double GetBucketSize(Count current, size_t i) const;
572
573  // If we have a description for a bucket, then return that.  Otherwise
574  // let parent class provide a (numeric) description.
575  virtual const std::string GetAsciiBucketRange(size_t i) const;
576
577  // Skip printing of name for numeric range if we have a name (and if this is
578  // an empty bucket).
579  virtual bool PrintEmptyBucket(size_t index) const;
580
581 private:
582  // For some ranges, we store a printable description of a bucket range.
583  // If there is no desciption, then GetAsciiBucketRange() uses parent class
584  // to provide a description.
585  typedef std::map<Sample, std::string> BucketDescriptionMap;
586  BucketDescriptionMap bucket_description_;
587
588  DISALLOW_COPY_AND_ASSIGN(LinearHistogram);
589};
590
591//------------------------------------------------------------------------------
592
593// BooleanHistogram is a histogram for booleans.
594class BooleanHistogram : public LinearHistogram {
595 public:
596  static scoped_refptr<Histogram> FactoryGet(const std::string& name,
597      Flags flags);
598
599  virtual ClassType histogram_type() const;
600
601  virtual void AddBoolean(bool value);
602
603 private:
604  explicit BooleanHistogram(const std::string& name);
605
606  DISALLOW_COPY_AND_ASSIGN(BooleanHistogram);
607};
608
609//------------------------------------------------------------------------------
610
611// CustomHistogram is a histogram for a set of custom integers.
612class CustomHistogram : public Histogram {
613 public:
614
615  static scoped_refptr<Histogram> FactoryGet(const std::string& name,
616      const std::vector<Sample>& custom_ranges, Flags flags);
617
618  // Overridden from Histogram:
619  virtual ClassType histogram_type() const;
620
621 protected:
622  CustomHistogram(const std::string& name,
623                  const std::vector<Sample>& custom_ranges);
624
625  // Initialize ranges_ mapping.
626  virtual void InitializeBucketRange();
627  virtual double GetBucketSize(Count current, size_t i) const;
628
629 private:
630  // Temporary pointer used during construction/initialization, and then NULLed.
631  const std::vector<Sample>* ranges_vector_;
632
633  DISALLOW_COPY_AND_ASSIGN(CustomHistogram);
634};
635
636//------------------------------------------------------------------------------
637// StatisticsRecorder handles all histograms in the system.  It provides a
638// general place for histograms to register, and supports a global API for
639// accessing (i.e., dumping, or graphing) the data in all the histograms.
640
641class StatisticsRecorder {
642 public:
643  typedef std::vector<scoped_refptr<Histogram> > Histograms;
644
645  StatisticsRecorder();
646
647  ~StatisticsRecorder();
648
649  // Find out if histograms can now be registered into our list.
650  static bool IsActive();
651
652  // Register, or add a new histogram to the collection of statistics.
653  static void Register(Histogram* histogram);
654
655  // Methods for printing histograms.  Only histograms which have query as
656  // a substring are written to output (an empty string will process all
657  // registered histograms).
658  static void WriteHTMLGraph(const std::string& query, std::string* output);
659  static void WriteGraph(const std::string& query, std::string* output);
660
661  // Method for extracting histograms which were marked for use by UMA.
662  static void GetHistograms(Histograms* output);
663
664  // Find a histogram by name. It matches the exact name. This method is thread
665  // safe.  If a matching histogram is not found, then the |histogram| is
666  // not changed.
667  static bool FindHistogram(const std::string& query,
668                            scoped_refptr<Histogram>* histogram);
669
670  static bool dump_on_exit() { return dump_on_exit_; }
671
672  static void set_dump_on_exit(bool enable) { dump_on_exit_ = enable; }
673
674  // GetSnapshot copies some of the pointers to registered histograms into the
675  // caller supplied vector (Histograms).  Only histograms with names matching
676  // query are returned. The query must be a substring of histogram name for its
677  // pointer to be copied.
678  static void GetSnapshot(const std::string& query, Histograms* snapshot);
679
680
681 private:
682  // We keep all registered histograms in a map, from name to histogram.
683  typedef std::map<std::string, scoped_refptr<Histogram> > HistogramMap;
684
685  static HistogramMap* histograms_;
686
687  // lock protects access to the above map.
688  static base::Lock* lock_;
689
690  // Dump all known histograms to log.
691  static bool dump_on_exit_;
692
693  DISALLOW_COPY_AND_ASSIGN(StatisticsRecorder);
694};
695
696}  // namespace base
697
698#endif  // BASE_METRICS_HISTOGRAM_H_
699