1 // Copyright (c) 2012 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.
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 // See header file for details and examples.
10 #include "base/metrics/histogram.h"
17 #include "base/compiler_specific.h"
18 #include "base/debug/alias.h"
19 #include "base/logging.h"
20 #include "base/metrics/sample_vector.h"
21 #include "base/metrics/statistics_recorder.h"
22 #include "base/pickle.h"
23 #include "base/string_util.h"
24 #include "base/stringprintf.h"
25 #include "base/synchronization/lock.h"
26 #include "base/values.h"
35 bool ReadHistogramArguments(PickleIterator
* iter
,
36 string
* histogram_name
,
41 uint32
* range_checksum
) {
42 if (!iter
->ReadString(histogram_name
) ||
43 !iter
->ReadInt(flags
) ||
44 !iter
->ReadInt(declared_min
) ||
45 !iter
->ReadInt(declared_max
) ||
46 !iter
->ReadUInt64(bucket_count
) ||
47 !iter
->ReadUInt32(range_checksum
)) {
48 DLOG(ERROR
) << "Pickle error decoding Histogram: " << *histogram_name
;
52 // Since these fields may have come from an untrusted renderer, do additional
53 // checks above and beyond those in Histogram::Initialize()
54 if (*declared_max
<= 0 ||
56 *declared_max
< *declared_min
||
57 INT_MAX
/ sizeof(HistogramBase::Count
) <= *bucket_count
||
59 DLOG(ERROR
) << "Values error decoding Histogram: " << histogram_name
;
63 // We use the arguments to find or create the local version of the histogram
64 // in this process, so we need to clear the IPC flag.
65 DCHECK(*flags
& HistogramBase::kIPCSerializationSourceFlag
);
66 *flags
&= ~HistogramBase::kIPCSerializationSourceFlag
;
71 bool ValidateRangeChecksum(const HistogramBase
& histogram
,
72 uint32 range_checksum
) {
73 const Histogram
& casted_histogram
=
74 static_cast<const Histogram
&>(histogram
);
76 return casted_histogram
.bucket_ranges()->checksum() == range_checksum
;
81 typedef HistogramBase::Count Count
;
82 typedef HistogramBase::Sample Sample
;
85 const size_t Histogram::kBucketCount_MAX
= 16384u;
87 // TODO(rtenneti): delete this code after debugging.
88 void CheckCorruption(const Histogram
& histogram
, bool new_histogram
) {
89 const std::string
& histogram_name
= histogram
.histogram_name();
90 char histogram_name_buf
[128];
91 base::strlcpy(histogram_name_buf
,
92 histogram_name
.c_str(),
93 arraysize(histogram_name_buf
));
94 base::debug::Alias(histogram_name_buf
);
96 bool debug_new_histogram
[1];
97 debug_new_histogram
[0] = new_histogram
;
98 base::debug::Alias(debug_new_histogram
);
100 Sample previous_range
= -1; // Bottom range is always 0.
101 for (size_t index
= 0; index
< histogram
.bucket_count(); ++index
) {
102 int new_range
= histogram
.ranges(index
);
103 CHECK_LT(previous_range
, new_range
);
104 previous_range
= new_range
;
107 CHECK(histogram
.bucket_ranges()->HasValidChecksum());
110 HistogramBase
* Histogram::FactoryGet(const string
& name
,
115 bool valid_arguments
=
116 InspectConstructionArguments(name
, &minimum
, &maximum
, &bucket_count
);
117 DCHECK(valid_arguments
);
119 Histogram
* histogram
= StatisticsRecorder::FindHistogram(name
);
121 // To avoid racy destruction at shutdown, the following will be leaked.
122 BucketRanges
* ranges
= new BucketRanges(bucket_count
+ 1);
123 InitializeBucketRanges(minimum
, maximum
, bucket_count
, ranges
);
124 const BucketRanges
* registered_ranges
=
125 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
127 Histogram
* tentative_histogram
=
128 new Histogram(name
, minimum
, maximum
, bucket_count
, registered_ranges
);
129 CheckCorruption(*tentative_histogram
, true);
131 tentative_histogram
->SetFlags(flags
);
133 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
135 // TODO(rtenneti): delete this code after debugging.
136 CheckCorruption(*histogram
, false);
138 CHECK_EQ(HISTOGRAM
, histogram
->GetHistogramType());
139 CHECK(histogram
->HasConstructionArguments(minimum
, maximum
, bucket_count
));
143 HistogramBase
* Histogram::FactoryTimeGet(const string
& name
,
148 return FactoryGet(name
, minimum
.InMilliseconds(), maximum
.InMilliseconds(),
149 bucket_count
, flags
);
152 TimeTicks
Histogram::DebugNow() {
154 return TimeTicks::Now();
160 // Calculate what range of values are held in each bucket.
161 // We have to be careful that we don't pick a ratio between starting points in
162 // consecutive buckets that is sooo small, that the integer bounds are the same
163 // (effectively making one bucket get no values). We need to avoid:
164 // ranges(i) == ranges(i + 1)
165 // To avoid that, we just do a fine-grained bucket width as far as we need to
166 // until we get a ratio that moves us along at least 2 units at a time. From
167 // that bucket onward we do use the exponential growth of buckets.
170 void Histogram::InitializeBucketRanges(Sample minimum
,
173 BucketRanges
* ranges
) {
174 DCHECK_EQ(ranges
->size(), bucket_count
+ 1);
175 double log_max
= log(static_cast<double>(maximum
));
178 size_t bucket_index
= 1;
179 Sample current
= minimum
;
180 ranges
->set_range(bucket_index
, current
);
181 while (bucket_count
> ++bucket_index
) {
183 log_current
= log(static_cast<double>(current
));
184 // Calculate the count'th root of the range.
185 log_ratio
= (log_max
- log_current
) / (bucket_count
- bucket_index
);
186 // See where the next bucket would start.
187 log_next
= log_current
+ log_ratio
;
189 next
= static_cast<int>(floor(exp(log_next
) + 0.5));
193 ++current
; // Just do a narrow bucket, and keep trying.
194 ranges
->set_range(bucket_index
, current
);
196 ranges
->set_range(ranges
->size() - 1, HistogramBase::kSampleType_MAX
);
197 ranges
->ResetChecksum();
201 const int Histogram::kCommonRaceBasedCountMismatch
= 5;
203 Histogram::Inconsistencies
Histogram::FindCorruption(
204 const HistogramSamples
& samples
) const {
205 int inconsistencies
= NO_INCONSISTENCIES
;
206 Sample previous_range
= -1; // Bottom range is always 0.
207 for (size_t index
= 0; index
< bucket_count(); ++index
) {
208 int new_range
= ranges(index
);
209 if (previous_range
>= new_range
)
210 inconsistencies
|= BUCKET_ORDER_ERROR
;
211 previous_range
= new_range
;
214 if (!bucket_ranges()->HasValidChecksum())
215 inconsistencies
|= RANGE_CHECKSUM_ERROR
;
217 int64 delta64
= samples
.redundant_count() - samples
.TotalCount();
219 int delta
= static_cast<int>(delta64
);
220 if (delta
!= delta64
)
221 delta
= INT_MAX
; // Flag all giant errors as INT_MAX.
223 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta
);
224 if (delta
> kCommonRaceBasedCountMismatch
)
225 inconsistencies
|= COUNT_HIGH_ERROR
;
228 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta
);
229 if (-delta
> kCommonRaceBasedCountMismatch
)
230 inconsistencies
|= COUNT_LOW_ERROR
;
233 return static_cast<Inconsistencies
>(inconsistencies
);
236 Sample
Histogram::ranges(size_t i
) const {
237 return bucket_ranges_
->range(i
);
240 size_t Histogram::bucket_count() const {
241 return bucket_count_
;
245 bool Histogram::InspectConstructionArguments(const string
& name
,
248 size_t* bucket_count
) {
249 // Defensive code for backward compatibility.
251 DVLOG(1) << "Histogram: " << name
<< " has bad minimum: " << *minimum
;
254 if (*maximum
>= kSampleType_MAX
) {
255 DVLOG(1) << "Histogram: " << name
<< " has bad maximum: " << *maximum
;
256 *maximum
= kSampleType_MAX
- 1;
258 if (*bucket_count
>= kBucketCount_MAX
) {
259 DVLOG(1) << "Histogram: " << name
<< " has bad bucket_count: "
261 *bucket_count
= kBucketCount_MAX
- 1;
264 if (*minimum
>= *maximum
)
266 if (*bucket_count
< 3)
268 if (*bucket_count
> static_cast<size_t>(*maximum
- *minimum
+ 2))
273 HistogramType
Histogram::GetHistogramType() const {
277 bool Histogram::HasConstructionArguments(Sample minimum
,
279 size_t bucket_count
) const {
280 return ((minimum
== declared_min_
) && (maximum
== declared_max_
) &&
281 (bucket_count
== bucket_count_
));
284 void Histogram::Add(int value
) {
285 DCHECK_EQ(0, ranges(0));
286 DCHECK_EQ(kSampleType_MAX
, ranges(bucket_count_
));
288 if (value
> kSampleType_MAX
- 1)
289 value
= kSampleType_MAX
- 1;
292 samples_
->Accumulate(value
, 1);
295 scoped_ptr
<HistogramSamples
> Histogram::SnapshotSamples() const {
296 return SnapshotSampleVector().PassAs
<HistogramSamples
>();
299 void Histogram::AddSamples(const HistogramSamples
& samples
) {
300 samples_
->Add(samples
);
303 bool Histogram::AddSamplesFromPickle(PickleIterator
* iter
) {
304 return samples_
->AddFromPickle(iter
);
307 // The following methods provide a graphical histogram display.
308 void Histogram::WriteHTMLGraph(string
* output
) const {
309 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
310 output
->append("<PRE>");
311 WriteAsciiImpl(true, "<br>", output
);
312 output
->append("</PRE>");
315 void Histogram::WriteAscii(string
* output
) const {
316 WriteAsciiImpl(true, "\n", output
);
319 bool Histogram::SerializeInfoImpl(Pickle
* pickle
) const {
320 DCHECK(bucket_ranges()->HasValidChecksum());
321 return pickle
->WriteString(histogram_name()) &&
322 pickle
->WriteInt(flags()) &&
323 pickle
->WriteInt(declared_min()) &&
324 pickle
->WriteInt(declared_max()) &&
325 pickle
->WriteUInt64(bucket_count()) &&
326 pickle
->WriteUInt32(bucket_ranges()->checksum());
329 Histogram::Histogram(const string
& name
,
333 const BucketRanges
* ranges
)
334 : HistogramBase(name
),
335 bucket_ranges_(ranges
),
336 declared_min_(minimum
),
337 declared_max_(maximum
),
338 bucket_count_(bucket_count
) {
340 samples_
.reset(new SampleVector(ranges
));
343 Histogram::~Histogram() {
344 if (StatisticsRecorder::dump_on_exit()) {
346 WriteAsciiImpl(true, "\n", &output
);
347 DLOG(INFO
) << output
;
351 bool Histogram::PrintEmptyBucket(size_t index
) const {
355 // Use the actual bucket widths (like a linear histogram) until the widths get
356 // over some transition value, and then use that transition width. Exponentials
357 // get so big so fast (and we don't expect to see a lot of entries in the large
358 // buckets), so we need this to make it possible to see what is going on and
359 // not have 0-graphical-height buckets.
360 double Histogram::GetBucketSize(Count current
, size_t i
) const {
361 DCHECK_GT(ranges(i
+ 1), ranges(i
));
362 static const double kTransitionWidth
= 5;
363 double denominator
= ranges(i
+ 1) - ranges(i
);
364 if (denominator
> kTransitionWidth
)
365 denominator
= kTransitionWidth
; // Stop trying to normalize.
366 return current
/denominator
;
369 const string
Histogram::GetAsciiBucketRange(size_t i
) const {
371 if (kHexRangePrintingFlag
& flags())
372 StringAppendF(&result
, "%#x", ranges(i
));
374 StringAppendF(&result
, "%d", ranges(i
));
378 //------------------------------------------------------------------------------
382 HistogramBase
* Histogram::DeserializeInfoImpl(PickleIterator
* iter
) {
383 string histogram_name
;
388 uint32 range_checksum
;
390 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
391 &declared_max
, &bucket_count
, &range_checksum
)) {
395 // Find or create the local version of the histogram in this process.
396 HistogramBase
* histogram
= Histogram::FactoryGet(
397 histogram_name
, declared_min
, declared_max
, bucket_count
, flags
);
399 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
400 // The serialized histogram might be corrupted.
406 scoped_ptr
<SampleVector
> Histogram::SnapshotSampleVector() const {
407 scoped_ptr
<SampleVector
> samples(new SampleVector(bucket_ranges()));
408 samples
->Add(*samples_
);
409 return samples
.Pass();
412 void Histogram::WriteAsciiImpl(bool graph_it
,
413 const string
& newline
,
414 string
* output
) const {
415 // Get local (stack) copies of all effectively volatile class data so that we
416 // are consistent across our output activities.
417 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
418 Count sample_count
= snapshot
->TotalCount();
420 WriteAsciiHeader(*snapshot
, sample_count
, output
);
421 output
->append(newline
);
423 // Prepare to normalize graphical rendering of bucket contents.
426 max_size
= GetPeakBucketSize(*snapshot
);
428 // Calculate space needed to print bucket range numbers. Leave room to print
429 // nearly the largest bucket range without sliding over the histogram.
430 size_t largest_non_empty_bucket
= bucket_count() - 1;
431 while (0 == snapshot
->GetCountAtIndex(largest_non_empty_bucket
)) {
432 if (0 == largest_non_empty_bucket
)
433 break; // All buckets are empty.
434 --largest_non_empty_bucket
;
437 // Calculate largest print width needed for any of our bucket range displays.
438 size_t print_width
= 1;
439 for (size_t i
= 0; i
< bucket_count(); ++i
) {
440 if (snapshot
->GetCountAtIndex(i
)) {
441 size_t width
= GetAsciiBucketRange(i
).size() + 1;
442 if (width
> print_width
)
447 int64 remaining
= sample_count
;
449 // Output the actual histogram graph.
450 for (size_t i
= 0; i
< bucket_count(); ++i
) {
451 Count current
= snapshot
->GetCountAtIndex(i
);
452 if (!current
&& !PrintEmptyBucket(i
))
454 remaining
-= current
;
455 string range
= GetAsciiBucketRange(i
);
456 output
->append(range
);
457 for (size_t j
= 0; range
.size() + j
< print_width
+ 1; ++j
)
458 output
->push_back(' ');
459 if (0 == current
&& i
< bucket_count() - 1 &&
460 0 == snapshot
->GetCountAtIndex(i
+ 1)) {
461 while (i
< bucket_count() - 1 &&
462 0 == snapshot
->GetCountAtIndex(i
+ 1)) {
465 output
->append("... ");
466 output
->append(newline
);
467 continue; // No reason to plot emptiness.
469 double current_size
= GetBucketSize(current
, i
);
471 WriteAsciiBucketGraph(current_size
, max_size
, output
);
472 WriteAsciiBucketContext(past
, current
, remaining
, i
, output
);
473 output
->append(newline
);
476 DCHECK_EQ(sample_count
, past
);
479 double Histogram::GetPeakBucketSize(const SampleVector
& samples
) const {
481 for (size_t i
= 0; i
< bucket_count() ; ++i
) {
482 double current_size
= GetBucketSize(samples
.GetCountAtIndex(i
), i
);
483 if (current_size
> max
)
489 void Histogram::WriteAsciiHeader(const SampleVector
& samples
,
491 string
* output
) const {
492 StringAppendF(output
,
493 "Histogram: %s recorded %d samples",
494 histogram_name().c_str(),
496 if (0 == sample_count
) {
497 DCHECK_EQ(samples
.sum(), 0);
499 double average
= static_cast<float>(samples
.sum()) / sample_count
;
501 StringAppendF(output
, ", average = %.1f", average
);
503 if (flags() & ~kHexRangePrintingFlag
)
504 StringAppendF(output
, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag
);
507 void Histogram::WriteAsciiBucketContext(const int64 past
,
509 const int64 remaining
,
511 string
* output
) const {
512 double scaled_sum
= (past
+ current
+ remaining
) / 100.0;
513 WriteAsciiBucketValue(current
, scaled_sum
, output
);
515 double percentage
= past
/ scaled_sum
;
516 StringAppendF(output
, " {%3.1f%%}", percentage
);
520 void Histogram::WriteAsciiBucketValue(Count current
,
522 string
* output
) const {
523 StringAppendF(output
, " (%d = %3.1f%%)", current
, current
/scaled_sum
);
526 void Histogram::WriteAsciiBucketGraph(double current_size
,
528 string
* output
) const {
529 const int k_line_length
= 72; // Maximal horizontal width of graph.
530 int x_count
= static_cast<int>(k_line_length
* (current_size
/ max_size
)
532 int x_remainder
= k_line_length
- x_count
;
534 while (0 < x_count
--)
537 while (0 < x_remainder
--)
541 void Histogram::GetParameters(DictionaryValue
* params
) const {
542 params
->SetString("type", HistogramTypeToString(GetHistogramType()));
543 params
->SetInteger("min", declared_min());
544 params
->SetInteger("max", declared_max());
545 params
->SetInteger("bucket_count", static_cast<int>(bucket_count()));
548 void Histogram::GetCountAndBucketData(Count
* count
, ListValue
* buckets
) const {
549 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
550 *count
= snapshot
->TotalCount();
552 for (size_t i
= 0; i
< bucket_count(); ++i
) {
553 Sample count
= snapshot
->GetCountAtIndex(i
);
555 scoped_ptr
<DictionaryValue
> bucket_value(new DictionaryValue());
556 bucket_value
->SetInteger("low", ranges(i
));
557 if (i
!= bucket_count() - 1)
558 bucket_value
->SetInteger("high", ranges(i
+ 1));
559 bucket_value
->SetInteger("count", count
);
560 buckets
->Set(index
, bucket_value
.release());
566 //------------------------------------------------------------------------------
567 // LinearHistogram: This histogram uses a traditional set of evenly spaced
569 //------------------------------------------------------------------------------
571 LinearHistogram::~LinearHistogram() {}
573 HistogramBase
* LinearHistogram::FactoryGet(const string
& name
,
578 return FactoryGetWithRangeDescription(
579 name
, minimum
, maximum
, bucket_count
, flags
, NULL
);
582 HistogramBase
* LinearHistogram::FactoryTimeGet(const string
& name
,
587 return FactoryGet(name
, minimum
.InMilliseconds(), maximum
.InMilliseconds(),
588 bucket_count
, flags
);
591 HistogramBase
* LinearHistogram::FactoryGetWithRangeDescription(
592 const std::string
& name
,
597 const DescriptionPair descriptions
[]) {
598 bool valid_arguments
= Histogram::InspectConstructionArguments(
599 name
, &minimum
, &maximum
, &bucket_count
);
600 DCHECK(valid_arguments
);
602 Histogram
* histogram
= StatisticsRecorder::FindHistogram(name
);
604 // To avoid racy destruction at shutdown, the following will be leaked.
605 BucketRanges
* ranges
= new BucketRanges(bucket_count
+ 1);
606 InitializeBucketRanges(minimum
, maximum
, bucket_count
, ranges
);
607 const BucketRanges
* registered_ranges
=
608 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
610 LinearHistogram
* tentative_histogram
=
611 new LinearHistogram(name
, minimum
, maximum
, bucket_count
,
613 CheckCorruption(*tentative_histogram
, true);
615 // Set range descriptions.
617 for (int i
= 0; descriptions
[i
].description
; ++i
) {
618 tentative_histogram
->bucket_description_
[descriptions
[i
].sample
] =
619 descriptions
[i
].description
;
623 tentative_histogram
->SetFlags(flags
);
625 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
627 // TODO(rtenneti): delete this code after debugging.
628 CheckCorruption(*histogram
, false);
630 CHECK_EQ(LINEAR_HISTOGRAM
, histogram
->GetHistogramType());
631 CHECK(histogram
->HasConstructionArguments(minimum
, maximum
, bucket_count
));
635 HistogramType
LinearHistogram::GetHistogramType() const {
636 return LINEAR_HISTOGRAM
;
639 LinearHistogram::LinearHistogram(const string
& name
,
643 const BucketRanges
* ranges
)
644 : Histogram(name
, minimum
, maximum
, bucket_count
, ranges
) {
647 double LinearHistogram::GetBucketSize(Count current
, size_t i
) const {
648 DCHECK_GT(ranges(i
+ 1), ranges(i
));
649 // Adjacent buckets with different widths would have "surprisingly" many (few)
650 // samples in a histogram if we didn't normalize this way.
651 double denominator
= ranges(i
+ 1) - ranges(i
);
652 return current
/denominator
;
655 const string
LinearHistogram::GetAsciiBucketRange(size_t i
) const {
656 int range
= ranges(i
);
657 BucketDescriptionMap::const_iterator it
= bucket_description_
.find(range
);
658 if (it
== bucket_description_
.end())
659 return Histogram::GetAsciiBucketRange(i
);
663 bool LinearHistogram::PrintEmptyBucket(size_t index
) const {
664 return bucket_description_
.find(ranges(index
)) == bucket_description_
.end();
668 void LinearHistogram::InitializeBucketRanges(Sample minimum
,
671 BucketRanges
* ranges
) {
672 DCHECK_EQ(ranges
->size(), bucket_count
+ 1);
673 double min
= minimum
;
674 double max
= maximum
;
676 for (i
= 1; i
< bucket_count
; ++i
) {
677 double linear_range
=
678 (min
* (bucket_count
-1 - i
) + max
* (i
- 1)) / (bucket_count
- 2);
679 ranges
->set_range(i
, static_cast<Sample
>(linear_range
+ 0.5));
681 ranges
->set_range(ranges
->size() - 1, HistogramBase::kSampleType_MAX
);
682 ranges
->ResetChecksum();
686 HistogramBase
* LinearHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
687 string histogram_name
;
692 uint32 range_checksum
;
694 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
695 &declared_max
, &bucket_count
, &range_checksum
)) {
699 HistogramBase
* histogram
= LinearHistogram::FactoryGet(
700 histogram_name
, declared_min
, declared_max
, bucket_count
, flags
);
701 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
702 // The serialized histogram might be corrupted.
708 //------------------------------------------------------------------------------
709 // This section provides implementation for BooleanHistogram.
710 //------------------------------------------------------------------------------
712 HistogramBase
* BooleanHistogram::FactoryGet(const string
& name
, int32 flags
) {
713 Histogram
* histogram
= StatisticsRecorder::FindHistogram(name
);
715 // To avoid racy destruction at shutdown, the following will be leaked.
716 BucketRanges
* ranges
= new BucketRanges(4);
717 LinearHistogram::InitializeBucketRanges(1, 2, 3, ranges
);
718 const BucketRanges
* registered_ranges
=
719 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
721 BooleanHistogram
* tentative_histogram
=
722 new BooleanHistogram(name
, registered_ranges
);
723 CheckCorruption(*tentative_histogram
, true);
725 tentative_histogram
->SetFlags(flags
);
727 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
729 // TODO(rtenneti): delete this code after debugging.
730 CheckCorruption(*histogram
, false);
732 CHECK_EQ(BOOLEAN_HISTOGRAM
, histogram
->GetHistogramType());
736 HistogramType
BooleanHistogram::GetHistogramType() const {
737 return BOOLEAN_HISTOGRAM
;
740 BooleanHistogram::BooleanHistogram(const string
& name
,
741 const BucketRanges
* ranges
)
742 : LinearHistogram(name
, 1, 2, 3, ranges
) {}
744 HistogramBase
* BooleanHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
745 string histogram_name
;
750 uint32 range_checksum
;
752 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
753 &declared_max
, &bucket_count
, &range_checksum
)) {
757 HistogramBase
* histogram
= BooleanHistogram::FactoryGet(
758 histogram_name
, flags
);
759 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
760 // The serialized histogram might be corrupted.
766 //------------------------------------------------------------------------------
768 //------------------------------------------------------------------------------
770 HistogramBase
* CustomHistogram::FactoryGet(const string
& name
,
771 const vector
<Sample
>& custom_ranges
,
773 CHECK(ValidateCustomRanges(custom_ranges
));
775 Histogram
* histogram
= StatisticsRecorder::FindHistogram(name
);
777 BucketRanges
* ranges
= CreateBucketRangesFromCustomRanges(custom_ranges
);
778 const BucketRanges
* registered_ranges
=
779 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
781 // To avoid racy destruction at shutdown, the following will be leaked.
782 CustomHistogram
* tentative_histogram
=
783 new CustomHistogram(name
, registered_ranges
);
784 CheckCorruption(*tentative_histogram
, true);
786 tentative_histogram
->SetFlags(flags
);
789 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
791 // TODO(rtenneti): delete this code after debugging.
792 CheckCorruption(*histogram
, false);
794 CHECK_EQ(histogram
->GetHistogramType(), CUSTOM_HISTOGRAM
);
798 HistogramType
CustomHistogram::GetHistogramType() const {
799 return CUSTOM_HISTOGRAM
;
803 vector
<Sample
> CustomHistogram::ArrayToCustomRanges(
804 const Sample
* values
, size_t num_values
) {
805 vector
<Sample
> all_values
;
806 for (size_t i
= 0; i
< num_values
; ++i
) {
807 Sample value
= values
[i
];
808 all_values
.push_back(value
);
810 // Ensure that a guard bucket is added. If we end up with duplicate
811 // values, FactoryGet will take care of removing them.
812 all_values
.push_back(value
+ 1);
817 CustomHistogram::CustomHistogram(const string
& name
,
818 const BucketRanges
* ranges
)
821 ranges
->range(ranges
->size() - 2),
825 bool CustomHistogram::SerializeInfoImpl(Pickle
* pickle
) const {
826 if (!Histogram::SerializeInfoImpl(pickle
))
829 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
831 for (size_t i
= 1; i
< bucket_ranges()->size() - 1; ++i
) {
832 if (!pickle
->WriteInt(bucket_ranges()->range(i
)))
838 double CustomHistogram::GetBucketSize(Count current
, size_t i
) const {
843 HistogramBase
* CustomHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
844 string histogram_name
;
849 uint32 range_checksum
;
851 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
852 &declared_max
, &bucket_count
, &range_checksum
)) {
856 // First and last ranges are not serialized.
857 vector
<Sample
> sample_ranges(bucket_count
- 1);
859 for (size_t i
= 0; i
< sample_ranges
.size(); ++i
) {
860 if (!iter
->ReadInt(&sample_ranges
[i
]))
864 HistogramBase
* histogram
= CustomHistogram::FactoryGet(
865 histogram_name
, sample_ranges
, flags
);
866 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
867 // The serialized histogram might be corrupted.
874 bool CustomHistogram::ValidateCustomRanges(
875 const vector
<Sample
>& custom_ranges
) {
876 bool has_valid_range
= false;
877 for (size_t i
= 0; i
< custom_ranges
.size(); i
++) {
878 Sample sample
= custom_ranges
[i
];
879 if (sample
< 0 || sample
> HistogramBase::kSampleType_MAX
- 1)
882 has_valid_range
= true;
884 return has_valid_range
;
888 BucketRanges
* CustomHistogram::CreateBucketRangesFromCustomRanges(
889 const vector
<Sample
>& custom_ranges
) {
890 // Remove the duplicates in the custom ranges array.
891 vector
<int> ranges
= custom_ranges
;
892 ranges
.push_back(0); // Ensure we have a zero value.
893 ranges
.push_back(HistogramBase::kSampleType_MAX
);
894 std::sort(ranges
.begin(), ranges
.end());
895 ranges
.erase(std::unique(ranges
.begin(), ranges
.end()), ranges
.end());
897 BucketRanges
* bucket_ranges
= new BucketRanges(ranges
.size());
898 for (size_t i
= 0; i
< ranges
.size(); i
++) {
899 bucket_ranges
->set_range(i
, ranges
[i
]);
901 bucket_ranges
->ResetChecksum();
902 return bucket_ranges
;