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/histogram_macros.h"
21 #include "base/metrics/sample_vector.h"
22 #include "base/metrics/statistics_recorder.h"
23 #include "base/pickle.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/synchronization/lock.h"
27 #include "base/values.h"
33 bool ReadHistogramArguments(PickleIterator
* iter
,
34 std::string
* histogram_name
,
39 uint32
* range_checksum
) {
40 if (!iter
->ReadString(histogram_name
) ||
41 !iter
->ReadInt(flags
) ||
42 !iter
->ReadInt(declared_min
) ||
43 !iter
->ReadInt(declared_max
) ||
44 !iter
->ReadSizeT(bucket_count
) ||
45 !iter
->ReadUInt32(range_checksum
)) {
46 DLOG(ERROR
) << "Pickle error decoding Histogram: " << *histogram_name
;
50 // Since these fields may have come from an untrusted renderer, do additional
51 // checks above and beyond those in Histogram::Initialize()
52 if (*declared_max
<= 0 ||
54 *declared_max
< *declared_min
||
55 INT_MAX
/ sizeof(HistogramBase::Count
) <= *bucket_count
||
57 DLOG(ERROR
) << "Values error decoding Histogram: " << histogram_name
;
61 // We use the arguments to find or create the local version of the histogram
62 // in this process, so we need to clear the IPC flag.
63 DCHECK(*flags
& HistogramBase::kIPCSerializationSourceFlag
);
64 *flags
&= ~HistogramBase::kIPCSerializationSourceFlag
;
69 bool ValidateRangeChecksum(const HistogramBase
& histogram
,
70 uint32 range_checksum
) {
71 const Histogram
& casted_histogram
=
72 static_cast<const Histogram
&>(histogram
);
74 return casted_histogram
.bucket_ranges()->checksum() == range_checksum
;
79 typedef HistogramBase::Count Count
;
80 typedef HistogramBase::Sample Sample
;
83 const size_t Histogram::kBucketCount_MAX
= 16384u;
85 HistogramBase
* Histogram::FactoryGet(const std::string
& name
,
90 bool valid_arguments
=
91 InspectConstructionArguments(name
, &minimum
, &maximum
, &bucket_count
);
92 DCHECK(valid_arguments
);
94 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
96 // To avoid racy destruction at shutdown, the following will be leaked.
97 BucketRanges
* ranges
= new BucketRanges(bucket_count
+ 1);
98 InitializeBucketRanges(minimum
, maximum
, ranges
);
99 const BucketRanges
* registered_ranges
=
100 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
102 Histogram
* tentative_histogram
=
103 new Histogram(name
, minimum
, maximum
, registered_ranges
);
105 tentative_histogram
->SetFlags(flags
);
107 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
110 DCHECK_EQ(HISTOGRAM
, histogram
->GetHistogramType());
111 if (!histogram
->HasConstructionArguments(minimum
, maximum
, bucket_count
)) {
112 // The construction arguments do not match the existing histogram. This can
113 // come about if an extension updates in the middle of a chrome run and has
114 // changed one of them, or simply by bad code within Chrome itself. We
115 // return NULL here with the expectation that bad code in Chrome will crash
116 // on dereference, but extension/Pepper APIs will guard against NULL and not
118 DLOG(ERROR
) << "Histogram " << name
<< " has bad construction arguments";
124 HistogramBase
* Histogram::FactoryTimeGet(const std::string
& name
,
129 return FactoryGet(name
, static_cast<Sample
>(minimum
.InMilliseconds()),
130 static_cast<Sample
>(maximum
.InMilliseconds()), bucket_count
,
134 HistogramBase
* Histogram::FactoryGet(const char* name
,
139 return FactoryGet(std::string(name
), minimum
, maximum
, bucket_count
, flags
);
142 HistogramBase
* Histogram::FactoryTimeGet(const char* name
,
147 return FactoryTimeGet(std::string(name
), minimum
, maximum
, bucket_count
,
151 // Calculate what range of values are held in each bucket.
152 // We have to be careful that we don't pick a ratio between starting points in
153 // consecutive buckets that is sooo small, that the integer bounds are the same
154 // (effectively making one bucket get no values). We need to avoid:
155 // ranges(i) == ranges(i + 1)
156 // To avoid that, we just do a fine-grained bucket width as far as we need to
157 // until we get a ratio that moves us along at least 2 units at a time. From
158 // that bucket onward we do use the exponential growth of buckets.
161 void Histogram::InitializeBucketRanges(Sample minimum
,
163 BucketRanges
* ranges
) {
164 double log_max
= log(static_cast<double>(maximum
));
167 size_t bucket_index
= 1;
168 Sample current
= minimum
;
169 ranges
->set_range(bucket_index
, current
);
170 size_t bucket_count
= ranges
->bucket_count();
171 while (bucket_count
> ++bucket_index
) {
173 log_current
= log(static_cast<double>(current
));
174 // Calculate the count'th root of the range.
175 log_ratio
= (log_max
- log_current
) / (bucket_count
- bucket_index
);
176 // See where the next bucket would start.
177 log_next
= log_current
+ log_ratio
;
179 next
= static_cast<int>(floor(exp(log_next
) + 0.5));
183 ++current
; // Just do a narrow bucket, and keep trying.
184 ranges
->set_range(bucket_index
, current
);
186 ranges
->set_range(ranges
->bucket_count(), HistogramBase::kSampleType_MAX
);
187 ranges
->ResetChecksum();
191 const int Histogram::kCommonRaceBasedCountMismatch
= 5;
193 int Histogram::FindCorruption(const HistogramSamples
& samples
) const {
194 int inconsistencies
= NO_INCONSISTENCIES
;
195 Sample previous_range
= -1; // Bottom range is always 0.
196 for (size_t index
= 0; index
< bucket_count(); ++index
) {
197 int new_range
= ranges(index
);
198 if (previous_range
>= new_range
)
199 inconsistencies
|= BUCKET_ORDER_ERROR
;
200 previous_range
= new_range
;
203 if (!bucket_ranges()->HasValidChecksum())
204 inconsistencies
|= RANGE_CHECKSUM_ERROR
;
206 int64 delta64
= samples
.redundant_count() - samples
.TotalCount();
208 int delta
= static_cast<int>(delta64
);
209 if (delta
!= delta64
)
210 delta
= INT_MAX
; // Flag all giant errors as INT_MAX.
212 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta
);
213 if (delta
> kCommonRaceBasedCountMismatch
)
214 inconsistencies
|= COUNT_HIGH_ERROR
;
217 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta
);
218 if (-delta
> kCommonRaceBasedCountMismatch
)
219 inconsistencies
|= COUNT_LOW_ERROR
;
222 return inconsistencies
;
225 Sample
Histogram::ranges(size_t i
) const {
226 return bucket_ranges_
->range(i
);
229 size_t Histogram::bucket_count() const {
230 return bucket_ranges_
->bucket_count();
234 bool Histogram::InspectConstructionArguments(const std::string
& name
,
237 size_t* bucket_count
) {
238 // Defensive code for backward compatibility.
240 DVLOG(1) << "Histogram: " << name
<< " has bad minimum: " << *minimum
;
243 if (*maximum
>= kSampleType_MAX
) {
244 DVLOG(1) << "Histogram: " << name
<< " has bad maximum: " << *maximum
;
245 *maximum
= kSampleType_MAX
- 1;
247 if (*bucket_count
>= kBucketCount_MAX
) {
248 DVLOG(1) << "Histogram: " << name
<< " has bad bucket_count: "
250 *bucket_count
= kBucketCount_MAX
- 1;
253 if (*minimum
>= *maximum
)
255 if (*bucket_count
< 3)
257 if (*bucket_count
> static_cast<size_t>(*maximum
- *minimum
+ 2))
262 HistogramType
Histogram::GetHistogramType() const {
266 bool Histogram::HasConstructionArguments(Sample expected_minimum
,
267 Sample expected_maximum
,
268 size_t expected_bucket_count
) const {
269 return ((expected_minimum
== declared_min_
) &&
270 (expected_maximum
== declared_max_
) &&
271 (expected_bucket_count
== bucket_count()));
274 void Histogram::Add(int value
) {
278 void Histogram::AddCount(int value
, int count
) {
279 DCHECK_EQ(0, ranges(0));
280 DCHECK_EQ(kSampleType_MAX
, ranges(bucket_count()));
282 if (value
> kSampleType_MAX
- 1)
283 value
= kSampleType_MAX
- 1;
290 samples_
->Accumulate(value
, count
);
292 FindAndRunCallback(value
);
295 scoped_ptr
<HistogramSamples
> Histogram::SnapshotSamples() const {
296 return SnapshotSampleVector().Pass();
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(std::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(std::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
->WriteSizeT(bucket_count()) &&
326 pickle
->WriteUInt32(bucket_ranges()->checksum());
329 Histogram::Histogram(const std::string
& name
,
332 const BucketRanges
* ranges
)
333 : HistogramBase(name
),
334 bucket_ranges_(ranges
),
335 declared_min_(minimum
),
336 declared_max_(maximum
) {
338 samples_
.reset(new SampleVector(ranges
));
341 Histogram::~Histogram() {
344 bool Histogram::PrintEmptyBucket(size_t index
) const {
348 // Use the actual bucket widths (like a linear histogram) until the widths get
349 // over some transition value, and then use that transition width. Exponentials
350 // get so big so fast (and we don't expect to see a lot of entries in the large
351 // buckets), so we need this to make it possible to see what is going on and
352 // not have 0-graphical-height buckets.
353 double Histogram::GetBucketSize(Count current
, size_t i
) const {
354 DCHECK_GT(ranges(i
+ 1), ranges(i
));
355 static const double kTransitionWidth
= 5;
356 double denominator
= ranges(i
+ 1) - ranges(i
);
357 if (denominator
> kTransitionWidth
)
358 denominator
= kTransitionWidth
; // Stop trying to normalize.
359 return current
/denominator
;
362 const std::string
Histogram::GetAsciiBucketRange(size_t i
) const {
363 return GetSimpleAsciiBucketRange(ranges(i
));
366 //------------------------------------------------------------------------------
370 HistogramBase
* Histogram::DeserializeInfoImpl(PickleIterator
* iter
) {
371 std::string histogram_name
;
376 uint32 range_checksum
;
378 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
379 &declared_max
, &bucket_count
, &range_checksum
)) {
383 // Find or create the local version of the histogram in this process.
384 HistogramBase
* histogram
= Histogram::FactoryGet(
385 histogram_name
, declared_min
, declared_max
, bucket_count
, flags
);
387 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
388 // The serialized histogram might be corrupted.
394 scoped_ptr
<SampleVector
> Histogram::SnapshotSampleVector() const {
395 scoped_ptr
<SampleVector
> samples(new SampleVector(bucket_ranges()));
396 samples
->Add(*samples_
);
397 return samples
.Pass();
400 void Histogram::WriteAsciiImpl(bool graph_it
,
401 const std::string
& newline
,
402 std::string
* output
) const {
403 // Get local (stack) copies of all effectively volatile class data so that we
404 // are consistent across our output activities.
405 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
406 Count sample_count
= snapshot
->TotalCount();
408 WriteAsciiHeader(*snapshot
, sample_count
, output
);
409 output
->append(newline
);
411 // Prepare to normalize graphical rendering of bucket contents.
414 max_size
= GetPeakBucketSize(*snapshot
);
416 // Calculate space needed to print bucket range numbers. Leave room to print
417 // nearly the largest bucket range without sliding over the histogram.
418 size_t largest_non_empty_bucket
= bucket_count() - 1;
419 while (0 == snapshot
->GetCountAtIndex(largest_non_empty_bucket
)) {
420 if (0 == largest_non_empty_bucket
)
421 break; // All buckets are empty.
422 --largest_non_empty_bucket
;
425 // Calculate largest print width needed for any of our bucket range displays.
426 size_t print_width
= 1;
427 for (size_t i
= 0; i
< bucket_count(); ++i
) {
428 if (snapshot
->GetCountAtIndex(i
)) {
429 size_t width
= GetAsciiBucketRange(i
).size() + 1;
430 if (width
> print_width
)
435 int64 remaining
= sample_count
;
437 // Output the actual histogram graph.
438 for (size_t i
= 0; i
< bucket_count(); ++i
) {
439 Count current
= snapshot
->GetCountAtIndex(i
);
440 if (!current
&& !PrintEmptyBucket(i
))
442 remaining
-= current
;
443 std::string range
= GetAsciiBucketRange(i
);
444 output
->append(range
);
445 for (size_t j
= 0; range
.size() + j
< print_width
+ 1; ++j
)
446 output
->push_back(' ');
447 if (0 == current
&& i
< bucket_count() - 1 &&
448 0 == snapshot
->GetCountAtIndex(i
+ 1)) {
449 while (i
< bucket_count() - 1 &&
450 0 == snapshot
->GetCountAtIndex(i
+ 1)) {
453 output
->append("... ");
454 output
->append(newline
);
455 continue; // No reason to plot emptiness.
457 double current_size
= GetBucketSize(current
, i
);
459 WriteAsciiBucketGraph(current_size
, max_size
, output
);
460 WriteAsciiBucketContext(past
, current
, remaining
, i
, output
);
461 output
->append(newline
);
464 DCHECK_EQ(sample_count
, past
);
467 double Histogram::GetPeakBucketSize(const SampleVector
& samples
) const {
469 for (size_t i
= 0; i
< bucket_count() ; ++i
) {
470 double current_size
= GetBucketSize(samples
.GetCountAtIndex(i
), i
);
471 if (current_size
> max
)
477 void Histogram::WriteAsciiHeader(const SampleVector
& samples
,
479 std::string
* output
) const {
480 StringAppendF(output
,
481 "Histogram: %s recorded %d samples",
482 histogram_name().c_str(),
484 if (0 == sample_count
) {
485 DCHECK_EQ(samples
.sum(), 0);
487 double average
= static_cast<float>(samples
.sum()) / sample_count
;
489 StringAppendF(output
, ", average = %.1f", average
);
491 if (flags() & ~kHexRangePrintingFlag
)
492 StringAppendF(output
, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag
);
495 void Histogram::WriteAsciiBucketContext(const int64 past
,
497 const int64 remaining
,
499 std::string
* output
) const {
500 double scaled_sum
= (past
+ current
+ remaining
) / 100.0;
501 WriteAsciiBucketValue(current
, scaled_sum
, output
);
503 double percentage
= past
/ scaled_sum
;
504 StringAppendF(output
, " {%3.1f%%}", percentage
);
508 void Histogram::GetParameters(DictionaryValue
* params
) const {
509 params
->SetString("type", HistogramTypeToString(GetHistogramType()));
510 params
->SetInteger("min", declared_min());
511 params
->SetInteger("max", declared_max());
512 params
->SetInteger("bucket_count", static_cast<int>(bucket_count()));
515 void Histogram::GetCountAndBucketData(Count
* count
,
517 ListValue
* buckets
) const {
518 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
519 *count
= snapshot
->TotalCount();
520 *sum
= snapshot
->sum();
522 for (size_t i
= 0; i
< bucket_count(); ++i
) {
523 Sample count_at_index
= snapshot
->GetCountAtIndex(i
);
524 if (count_at_index
> 0) {
525 scoped_ptr
<DictionaryValue
> bucket_value(new DictionaryValue());
526 bucket_value
->SetInteger("low", ranges(i
));
527 if (i
!= bucket_count() - 1)
528 bucket_value
->SetInteger("high", ranges(i
+ 1));
529 bucket_value
->SetInteger("count", count_at_index
);
530 buckets
->Set(index
, bucket_value
.release());
536 //------------------------------------------------------------------------------
537 // LinearHistogram: This histogram uses a traditional set of evenly spaced
539 //------------------------------------------------------------------------------
541 LinearHistogram::~LinearHistogram() {}
543 HistogramBase
* LinearHistogram::FactoryGet(const std::string
& name
,
548 return FactoryGetWithRangeDescription(
549 name
, minimum
, maximum
, bucket_count
, flags
, NULL
);
552 HistogramBase
* LinearHistogram::FactoryTimeGet(const std::string
& name
,
557 return FactoryGet(name
, static_cast<Sample
>(minimum
.InMilliseconds()),
558 static_cast<Sample
>(maximum
.InMilliseconds()), bucket_count
,
562 HistogramBase
* LinearHistogram::FactoryGet(const char* name
,
567 return FactoryGet(std::string(name
), minimum
, maximum
, bucket_count
, flags
);
570 HistogramBase
* LinearHistogram::FactoryTimeGet(const char* name
,
575 return FactoryTimeGet(std::string(name
), minimum
, maximum
, bucket_count
,
579 HistogramBase
* LinearHistogram::FactoryGetWithRangeDescription(
580 const std::string
& name
,
585 const DescriptionPair descriptions
[]) {
586 bool valid_arguments
= Histogram::InspectConstructionArguments(
587 name
, &minimum
, &maximum
, &bucket_count
);
588 DCHECK(valid_arguments
);
590 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
592 // To avoid racy destruction at shutdown, the following will be leaked.
593 BucketRanges
* ranges
= new BucketRanges(bucket_count
+ 1);
594 InitializeBucketRanges(minimum
, maximum
, ranges
);
595 const BucketRanges
* registered_ranges
=
596 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
598 LinearHistogram
* tentative_histogram
=
599 new LinearHistogram(name
, minimum
, maximum
, registered_ranges
);
601 // Set range descriptions.
603 for (int i
= 0; descriptions
[i
].description
; ++i
) {
604 tentative_histogram
->bucket_description_
[descriptions
[i
].sample
] =
605 descriptions
[i
].description
;
609 tentative_histogram
->SetFlags(flags
);
611 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
614 DCHECK_EQ(LINEAR_HISTOGRAM
, histogram
->GetHistogramType());
615 if (!histogram
->HasConstructionArguments(minimum
, maximum
, bucket_count
)) {
616 // The construction arguments do not match the existing histogram. This can
617 // come about if an extension updates in the middle of a chrome run and has
618 // changed one of them, or simply by bad code within Chrome itself. We
619 // return NULL here with the expectation that bad code in Chrome will crash
620 // on dereference, but extension/Pepper APIs will guard against NULL and not
622 DLOG(ERROR
) << "Histogram " << name
<< " has bad construction arguments";
628 HistogramType
LinearHistogram::GetHistogramType() const {
629 return LINEAR_HISTOGRAM
;
632 LinearHistogram::LinearHistogram(const std::string
& name
,
635 const BucketRanges
* ranges
)
636 : Histogram(name
, minimum
, maximum
, ranges
) {
639 double LinearHistogram::GetBucketSize(Count current
, size_t i
) const {
640 DCHECK_GT(ranges(i
+ 1), ranges(i
));
641 // Adjacent buckets with different widths would have "surprisingly" many (few)
642 // samples in a histogram if we didn't normalize this way.
643 double denominator
= ranges(i
+ 1) - ranges(i
);
644 return current
/denominator
;
647 const std::string
LinearHistogram::GetAsciiBucketRange(size_t i
) const {
648 int range
= ranges(i
);
649 BucketDescriptionMap::const_iterator it
= bucket_description_
.find(range
);
650 if (it
== bucket_description_
.end())
651 return Histogram::GetAsciiBucketRange(i
);
655 bool LinearHistogram::PrintEmptyBucket(size_t index
) const {
656 return bucket_description_
.find(ranges(index
)) == bucket_description_
.end();
660 void LinearHistogram::InitializeBucketRanges(Sample minimum
,
662 BucketRanges
* ranges
) {
663 double min
= minimum
;
664 double max
= maximum
;
665 size_t bucket_count
= ranges
->bucket_count();
666 for (size_t i
= 1; i
< bucket_count
; ++i
) {
667 double linear_range
=
668 (min
* (bucket_count
- 1 - i
) + max
* (i
- 1)) / (bucket_count
- 2);
669 ranges
->set_range(i
, static_cast<Sample
>(linear_range
+ 0.5));
671 ranges
->set_range(ranges
->bucket_count(), HistogramBase::kSampleType_MAX
);
672 ranges
->ResetChecksum();
676 HistogramBase
* LinearHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
677 std::string histogram_name
;
682 uint32 range_checksum
;
684 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
685 &declared_max
, &bucket_count
, &range_checksum
)) {
689 HistogramBase
* histogram
= LinearHistogram::FactoryGet(
690 histogram_name
, declared_min
, declared_max
, bucket_count
, flags
);
691 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
692 // The serialized histogram might be corrupted.
698 //------------------------------------------------------------------------------
699 // This section provides implementation for BooleanHistogram.
700 //------------------------------------------------------------------------------
702 HistogramBase
* BooleanHistogram::FactoryGet(const std::string
& name
,
704 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
706 // To avoid racy destruction at shutdown, the following will be leaked.
707 BucketRanges
* ranges
= new BucketRanges(4);
708 LinearHistogram::InitializeBucketRanges(1, 2, ranges
);
709 const BucketRanges
* registered_ranges
=
710 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
712 BooleanHistogram
* tentative_histogram
=
713 new BooleanHistogram(name
, registered_ranges
);
715 tentative_histogram
->SetFlags(flags
);
717 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
720 DCHECK_EQ(BOOLEAN_HISTOGRAM
, histogram
->GetHistogramType());
724 HistogramBase
* BooleanHistogram::FactoryGet(const char* name
, int32 flags
) {
725 return FactoryGet(std::string(name
), flags
);
728 HistogramType
BooleanHistogram::GetHistogramType() const {
729 return BOOLEAN_HISTOGRAM
;
732 BooleanHistogram::BooleanHistogram(const std::string
& name
,
733 const BucketRanges
* ranges
)
734 : LinearHistogram(name
, 1, 2, ranges
) {}
736 HistogramBase
* BooleanHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
737 std::string histogram_name
;
742 uint32 range_checksum
;
744 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
745 &declared_max
, &bucket_count
, &range_checksum
)) {
749 HistogramBase
* histogram
= BooleanHistogram::FactoryGet(
750 histogram_name
, flags
);
751 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
752 // The serialized histogram might be corrupted.
758 //------------------------------------------------------------------------------
760 //------------------------------------------------------------------------------
762 HistogramBase
* CustomHistogram::FactoryGet(
763 const std::string
& name
,
764 const std::vector
<Sample
>& custom_ranges
,
766 CHECK(ValidateCustomRanges(custom_ranges
));
768 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
770 BucketRanges
* ranges
= CreateBucketRangesFromCustomRanges(custom_ranges
);
771 const BucketRanges
* registered_ranges
=
772 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
774 // To avoid racy destruction at shutdown, the following will be leaked.
775 CustomHistogram
* tentative_histogram
=
776 new CustomHistogram(name
, registered_ranges
);
778 tentative_histogram
->SetFlags(flags
);
781 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
784 DCHECK_EQ(histogram
->GetHistogramType(), CUSTOM_HISTOGRAM
);
788 HistogramBase
* CustomHistogram::FactoryGet(
790 const std::vector
<Sample
>& custom_ranges
,
792 return FactoryGet(std::string(name
), custom_ranges
, flags
);
795 HistogramType
CustomHistogram::GetHistogramType() const {
796 return CUSTOM_HISTOGRAM
;
800 std::vector
<Sample
> CustomHistogram::ArrayToCustomRanges(
801 const Sample
* values
, size_t num_values
) {
802 std::vector
<Sample
> all_values
;
803 for (size_t i
= 0; i
< num_values
; ++i
) {
804 Sample value
= values
[i
];
805 all_values
.push_back(value
);
807 // Ensure that a guard bucket is added. If we end up with duplicate
808 // values, FactoryGet will take care of removing them.
809 all_values
.push_back(value
+ 1);
814 CustomHistogram::CustomHistogram(const std::string
& name
,
815 const BucketRanges
* ranges
)
818 ranges
->range(ranges
->bucket_count() - 1),
821 bool CustomHistogram::SerializeInfoImpl(Pickle
* pickle
) const {
822 if (!Histogram::SerializeInfoImpl(pickle
))
825 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
827 for (size_t i
= 1; i
< bucket_ranges()->bucket_count(); ++i
) {
828 if (!pickle
->WriteInt(bucket_ranges()->range(i
)))
834 double CustomHistogram::GetBucketSize(Count current
, size_t i
) const {
839 HistogramBase
* CustomHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
840 std::string histogram_name
;
845 uint32 range_checksum
;
847 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
848 &declared_max
, &bucket_count
, &range_checksum
)) {
852 // First and last ranges are not serialized.
853 std::vector
<Sample
> sample_ranges(bucket_count
- 1);
855 for (size_t i
= 0; i
< sample_ranges
.size(); ++i
) {
856 if (!iter
->ReadInt(&sample_ranges
[i
]))
860 HistogramBase
* histogram
= CustomHistogram::FactoryGet(
861 histogram_name
, sample_ranges
, flags
);
862 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
863 // The serialized histogram might be corrupted.
870 bool CustomHistogram::ValidateCustomRanges(
871 const std::vector
<Sample
>& custom_ranges
) {
872 bool has_valid_range
= false;
873 for (size_t i
= 0; i
< custom_ranges
.size(); i
++) {
874 Sample sample
= custom_ranges
[i
];
875 if (sample
< 0 || sample
> HistogramBase::kSampleType_MAX
- 1)
878 has_valid_range
= true;
880 return has_valid_range
;
884 BucketRanges
* CustomHistogram::CreateBucketRangesFromCustomRanges(
885 const std::vector
<Sample
>& custom_ranges
) {
886 // Remove the duplicates in the custom ranges array.
887 std::vector
<int> ranges
= custom_ranges
;
888 ranges
.push_back(0); // Ensure we have a zero value.
889 ranges
.push_back(HistogramBase::kSampleType_MAX
);
890 std::sort(ranges
.begin(), ranges
.end());
891 ranges
.erase(std::unique(ranges
.begin(), ranges
.end()), ranges
.end());
893 BucketRanges
* bucket_ranges
= new BucketRanges(ranges
.size());
894 for (size_t i
= 0; i
< ranges
.size(); i
++) {
895 bucket_ranges
->set_range(i
, ranges
[i
]);
897 bucket_ranges
->ResetChecksum();
898 return bucket_ranges
;