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 HistogramBase
* Histogram::FactoryGet(const string
& name
,
92 bool valid_arguments
=
93 InspectConstructionArguments(name
, &minimum
, &maximum
, &bucket_count
);
94 DCHECK(valid_arguments
);
96 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
98 // To avoid racy destruction at shutdown, the following will be leaked.
99 BucketRanges
* ranges
= new BucketRanges(bucket_count
+ 1);
100 InitializeBucketRanges(minimum
, maximum
, bucket_count
, ranges
);
101 const BucketRanges
* registered_ranges
=
102 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
104 Histogram
* tentative_histogram
=
105 new Histogram(name
, minimum
, maximum
, bucket_count
, registered_ranges
);
107 tentative_histogram
->SetFlags(flags
);
109 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
112 DCHECK_EQ(HISTOGRAM
, histogram
->GetHistogramType());
113 CHECK(histogram
->HasConstructionArguments(minimum
, maximum
, bucket_count
));
117 HistogramBase
* Histogram::FactoryTimeGet(const string
& name
,
122 return FactoryGet(name
, minimum
.InMilliseconds(), maximum
.InMilliseconds(),
123 bucket_count
, flags
);
126 TimeTicks
Histogram::DebugNow() {
128 return TimeTicks::Now();
134 // Calculate what range of values are held in each bucket.
135 // We have to be careful that we don't pick a ratio between starting points in
136 // consecutive buckets that is sooo small, that the integer bounds are the same
137 // (effectively making one bucket get no values). We need to avoid:
138 // ranges(i) == ranges(i + 1)
139 // To avoid that, we just do a fine-grained bucket width as far as we need to
140 // until we get a ratio that moves us along at least 2 units at a time. From
141 // that bucket onward we do use the exponential growth of buckets.
144 void Histogram::InitializeBucketRanges(Sample minimum
,
147 BucketRanges
* ranges
) {
148 DCHECK_EQ(ranges
->size(), bucket_count
+ 1);
149 double log_max
= log(static_cast<double>(maximum
));
152 size_t bucket_index
= 1;
153 Sample current
= minimum
;
154 ranges
->set_range(bucket_index
, current
);
155 while (bucket_count
> ++bucket_index
) {
157 log_current
= log(static_cast<double>(current
));
158 // Calculate the count'th root of the range.
159 log_ratio
= (log_max
- log_current
) / (bucket_count
- bucket_index
);
160 // See where the next bucket would start.
161 log_next
= log_current
+ log_ratio
;
163 next
= static_cast<int>(floor(exp(log_next
) + 0.5));
167 ++current
; // Just do a narrow bucket, and keep trying.
168 ranges
->set_range(bucket_index
, current
);
170 ranges
->set_range(ranges
->size() - 1, HistogramBase::kSampleType_MAX
);
171 ranges
->ResetChecksum();
175 const int Histogram::kCommonRaceBasedCountMismatch
= 5;
177 int Histogram::FindCorruption(const HistogramSamples
& samples
) const {
178 int inconsistencies
= NO_INCONSISTENCIES
;
179 Sample previous_range
= -1; // Bottom range is always 0.
180 for (size_t index
= 0; index
< bucket_count(); ++index
) {
181 int new_range
= ranges(index
);
182 if (previous_range
>= new_range
)
183 inconsistencies
|= BUCKET_ORDER_ERROR
;
184 previous_range
= new_range
;
187 if (!bucket_ranges()->HasValidChecksum())
188 inconsistencies
|= RANGE_CHECKSUM_ERROR
;
190 int64 delta64
= samples
.redundant_count() - samples
.TotalCount();
192 int delta
= static_cast<int>(delta64
);
193 if (delta
!= delta64
)
194 delta
= INT_MAX
; // Flag all giant errors as INT_MAX.
196 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta
);
197 if (delta
> kCommonRaceBasedCountMismatch
)
198 inconsistencies
|= COUNT_HIGH_ERROR
;
201 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta
);
202 if (-delta
> kCommonRaceBasedCountMismatch
)
203 inconsistencies
|= COUNT_LOW_ERROR
;
206 return inconsistencies
;
209 Sample
Histogram::ranges(size_t i
) const {
210 return bucket_ranges_
->range(i
);
213 size_t Histogram::bucket_count() const {
214 return bucket_count_
;
218 bool Histogram::InspectConstructionArguments(const string
& name
,
221 size_t* bucket_count
) {
222 // Defensive code for backward compatibility.
224 DVLOG(1) << "Histogram: " << name
<< " has bad minimum: " << *minimum
;
227 if (*maximum
>= kSampleType_MAX
) {
228 DVLOG(1) << "Histogram: " << name
<< " has bad maximum: " << *maximum
;
229 *maximum
= kSampleType_MAX
- 1;
231 if (*bucket_count
>= kBucketCount_MAX
) {
232 DVLOG(1) << "Histogram: " << name
<< " has bad bucket_count: "
234 *bucket_count
= kBucketCount_MAX
- 1;
237 if (*minimum
>= *maximum
)
239 if (*bucket_count
< 3)
241 if (*bucket_count
> static_cast<size_t>(*maximum
- *minimum
+ 2))
246 HistogramType
Histogram::GetHistogramType() const {
250 bool Histogram::HasConstructionArguments(Sample minimum
,
252 size_t bucket_count
) const {
253 return ((minimum
== declared_min_
) && (maximum
== declared_max_
) &&
254 (bucket_count
== bucket_count_
));
257 void Histogram::Add(int value
) {
258 DCHECK_EQ(0, ranges(0));
259 DCHECK_EQ(kSampleType_MAX
, ranges(bucket_count_
));
261 if (value
> kSampleType_MAX
- 1)
262 value
= kSampleType_MAX
- 1;
265 samples_
->Accumulate(value
, 1);
268 scoped_ptr
<HistogramSamples
> Histogram::SnapshotSamples() const {
269 return SnapshotSampleVector().PassAs
<HistogramSamples
>();
272 void Histogram::AddSamples(const HistogramSamples
& samples
) {
273 samples_
->Add(samples
);
276 bool Histogram::AddSamplesFromPickle(PickleIterator
* iter
) {
277 return samples_
->AddFromPickle(iter
);
280 // The following methods provide a graphical histogram display.
281 void Histogram::WriteHTMLGraph(string
* output
) const {
282 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
283 output
->append("<PRE>");
284 WriteAsciiImpl(true, "<br>", output
);
285 output
->append("</PRE>");
288 void Histogram::WriteAscii(string
* output
) const {
289 WriteAsciiImpl(true, "\n", output
);
292 bool Histogram::SerializeInfoImpl(Pickle
* pickle
) const {
293 DCHECK(bucket_ranges()->HasValidChecksum());
294 return pickle
->WriteString(histogram_name()) &&
295 pickle
->WriteInt(flags()) &&
296 pickle
->WriteInt(declared_min()) &&
297 pickle
->WriteInt(declared_max()) &&
298 pickle
->WriteUInt64(bucket_count()) &&
299 pickle
->WriteUInt32(bucket_ranges()->checksum());
302 Histogram::Histogram(const string
& name
,
306 const BucketRanges
* ranges
)
307 : HistogramBase(name
),
308 bucket_ranges_(ranges
),
309 declared_min_(minimum
),
310 declared_max_(maximum
),
311 bucket_count_(bucket_count
) {
313 samples_
.reset(new SampleVector(ranges
));
316 Histogram::~Histogram() {
319 bool Histogram::PrintEmptyBucket(size_t index
) const {
323 // Use the actual bucket widths (like a linear histogram) until the widths get
324 // over some transition value, and then use that transition width. Exponentials
325 // get so big so fast (and we don't expect to see a lot of entries in the large
326 // buckets), so we need this to make it possible to see what is going on and
327 // not have 0-graphical-height buckets.
328 double Histogram::GetBucketSize(Count current
, size_t i
) const {
329 DCHECK_GT(ranges(i
+ 1), ranges(i
));
330 static const double kTransitionWidth
= 5;
331 double denominator
= ranges(i
+ 1) - ranges(i
);
332 if (denominator
> kTransitionWidth
)
333 denominator
= kTransitionWidth
; // Stop trying to normalize.
334 return current
/denominator
;
337 const string
Histogram::GetAsciiBucketRange(size_t i
) const {
338 return GetSimpleAsciiBucketRange(ranges(i
));
341 //------------------------------------------------------------------------------
345 HistogramBase
* Histogram::DeserializeInfoImpl(PickleIterator
* iter
) {
346 string histogram_name
;
351 uint32 range_checksum
;
353 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
354 &declared_max
, &bucket_count
, &range_checksum
)) {
358 // Find or create the local version of the histogram in this process.
359 HistogramBase
* histogram
= Histogram::FactoryGet(
360 histogram_name
, declared_min
, declared_max
, bucket_count
, flags
);
362 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
363 // The serialized histogram might be corrupted.
369 scoped_ptr
<SampleVector
> Histogram::SnapshotSampleVector() const {
370 scoped_ptr
<SampleVector
> samples(new SampleVector(bucket_ranges()));
371 samples
->Add(*samples_
);
372 return samples
.Pass();
375 void Histogram::WriteAsciiImpl(bool graph_it
,
376 const string
& newline
,
377 string
* output
) const {
378 // Get local (stack) copies of all effectively volatile class data so that we
379 // are consistent across our output activities.
380 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
381 Count sample_count
= snapshot
->TotalCount();
383 WriteAsciiHeader(*snapshot
, sample_count
, output
);
384 output
->append(newline
);
386 // Prepare to normalize graphical rendering of bucket contents.
389 max_size
= GetPeakBucketSize(*snapshot
);
391 // Calculate space needed to print bucket range numbers. Leave room to print
392 // nearly the largest bucket range without sliding over the histogram.
393 size_t largest_non_empty_bucket
= bucket_count() - 1;
394 while (0 == snapshot
->GetCountAtIndex(largest_non_empty_bucket
)) {
395 if (0 == largest_non_empty_bucket
)
396 break; // All buckets are empty.
397 --largest_non_empty_bucket
;
400 // Calculate largest print width needed for any of our bucket range displays.
401 size_t print_width
= 1;
402 for (size_t i
= 0; i
< bucket_count(); ++i
) {
403 if (snapshot
->GetCountAtIndex(i
)) {
404 size_t width
= GetAsciiBucketRange(i
).size() + 1;
405 if (width
> print_width
)
410 int64 remaining
= sample_count
;
412 // Output the actual histogram graph.
413 for (size_t i
= 0; i
< bucket_count(); ++i
) {
414 Count current
= snapshot
->GetCountAtIndex(i
);
415 if (!current
&& !PrintEmptyBucket(i
))
417 remaining
-= current
;
418 string range
= GetAsciiBucketRange(i
);
419 output
->append(range
);
420 for (size_t j
= 0; range
.size() + j
< print_width
+ 1; ++j
)
421 output
->push_back(' ');
422 if (0 == current
&& i
< bucket_count() - 1 &&
423 0 == snapshot
->GetCountAtIndex(i
+ 1)) {
424 while (i
< bucket_count() - 1 &&
425 0 == snapshot
->GetCountAtIndex(i
+ 1)) {
428 output
->append("... ");
429 output
->append(newline
);
430 continue; // No reason to plot emptiness.
432 double current_size
= GetBucketSize(current
, i
);
434 WriteAsciiBucketGraph(current_size
, max_size
, output
);
435 WriteAsciiBucketContext(past
, current
, remaining
, i
, output
);
436 output
->append(newline
);
439 DCHECK_EQ(sample_count
, past
);
442 double Histogram::GetPeakBucketSize(const SampleVector
& samples
) const {
444 for (size_t i
= 0; i
< bucket_count() ; ++i
) {
445 double current_size
= GetBucketSize(samples
.GetCountAtIndex(i
), i
);
446 if (current_size
> max
)
452 void Histogram::WriteAsciiHeader(const SampleVector
& samples
,
454 string
* output
) const {
455 StringAppendF(output
,
456 "Histogram: %s recorded %d samples",
457 histogram_name().c_str(),
459 if (0 == sample_count
) {
460 DCHECK_EQ(samples
.sum(), 0);
462 double average
= static_cast<float>(samples
.sum()) / sample_count
;
464 StringAppendF(output
, ", average = %.1f", average
);
466 if (flags() & ~kHexRangePrintingFlag
)
467 StringAppendF(output
, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag
);
470 void Histogram::WriteAsciiBucketContext(const int64 past
,
472 const int64 remaining
,
474 string
* output
) const {
475 double scaled_sum
= (past
+ current
+ remaining
) / 100.0;
476 WriteAsciiBucketValue(current
, scaled_sum
, output
);
478 double percentage
= past
/ scaled_sum
;
479 StringAppendF(output
, " {%3.1f%%}", percentage
);
483 void Histogram::GetParameters(DictionaryValue
* params
) const {
484 params
->SetString("type", HistogramTypeToString(GetHistogramType()));
485 params
->SetInteger("min", declared_min());
486 params
->SetInteger("max", declared_max());
487 params
->SetInteger("bucket_count", static_cast<int>(bucket_count()));
490 void Histogram::GetCountAndBucketData(Count
* count
,
492 ListValue
* buckets
) const {
493 scoped_ptr
<SampleVector
> snapshot
= SnapshotSampleVector();
494 *count
= snapshot
->TotalCount();
495 *sum
= snapshot
->sum();
497 for (size_t i
= 0; i
< bucket_count(); ++i
) {
498 Sample count
= snapshot
->GetCountAtIndex(i
);
500 scoped_ptr
<DictionaryValue
> bucket_value(new DictionaryValue());
501 bucket_value
->SetInteger("low", ranges(i
));
502 if (i
!= bucket_count() - 1)
503 bucket_value
->SetInteger("high", ranges(i
+ 1));
504 bucket_value
->SetInteger("count", count
);
505 buckets
->Set(index
, bucket_value
.release());
511 //------------------------------------------------------------------------------
512 // LinearHistogram: This histogram uses a traditional set of evenly spaced
514 //------------------------------------------------------------------------------
516 LinearHistogram::~LinearHistogram() {}
518 HistogramBase
* LinearHistogram::FactoryGet(const string
& name
,
523 return FactoryGetWithRangeDescription(
524 name
, minimum
, maximum
, bucket_count
, flags
, NULL
);
527 HistogramBase
* LinearHistogram::FactoryTimeGet(const string
& name
,
532 return FactoryGet(name
, minimum
.InMilliseconds(), maximum
.InMilliseconds(),
533 bucket_count
, flags
);
536 HistogramBase
* LinearHistogram::FactoryGetWithRangeDescription(
537 const std::string
& name
,
542 const DescriptionPair descriptions
[]) {
543 bool valid_arguments
= Histogram::InspectConstructionArguments(
544 name
, &minimum
, &maximum
, &bucket_count
);
545 DCHECK(valid_arguments
);
547 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
549 // To avoid racy destruction at shutdown, the following will be leaked.
550 BucketRanges
* ranges
= new BucketRanges(bucket_count
+ 1);
551 InitializeBucketRanges(minimum
, maximum
, bucket_count
, ranges
);
552 const BucketRanges
* registered_ranges
=
553 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
555 LinearHistogram
* tentative_histogram
=
556 new LinearHistogram(name
, minimum
, maximum
, bucket_count
,
559 // Set range descriptions.
561 for (int i
= 0; descriptions
[i
].description
; ++i
) {
562 tentative_histogram
->bucket_description_
[descriptions
[i
].sample
] =
563 descriptions
[i
].description
;
567 tentative_histogram
->SetFlags(flags
);
569 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
572 DCHECK_EQ(LINEAR_HISTOGRAM
, histogram
->GetHistogramType());
573 CHECK(histogram
->HasConstructionArguments(minimum
, maximum
, bucket_count
));
577 HistogramType
LinearHistogram::GetHistogramType() const {
578 return LINEAR_HISTOGRAM
;
581 LinearHistogram::LinearHistogram(const string
& name
,
585 const BucketRanges
* ranges
)
586 : Histogram(name
, minimum
, maximum
, bucket_count
, ranges
) {
589 double LinearHistogram::GetBucketSize(Count current
, size_t i
) const {
590 DCHECK_GT(ranges(i
+ 1), ranges(i
));
591 // Adjacent buckets with different widths would have "surprisingly" many (few)
592 // samples in a histogram if we didn't normalize this way.
593 double denominator
= ranges(i
+ 1) - ranges(i
);
594 return current
/denominator
;
597 const string
LinearHistogram::GetAsciiBucketRange(size_t i
) const {
598 int range
= ranges(i
);
599 BucketDescriptionMap::const_iterator it
= bucket_description_
.find(range
);
600 if (it
== bucket_description_
.end())
601 return Histogram::GetAsciiBucketRange(i
);
605 bool LinearHistogram::PrintEmptyBucket(size_t index
) const {
606 return bucket_description_
.find(ranges(index
)) == bucket_description_
.end();
610 void LinearHistogram::InitializeBucketRanges(Sample minimum
,
613 BucketRanges
* ranges
) {
614 DCHECK_EQ(ranges
->size(), bucket_count
+ 1);
615 double min
= minimum
;
616 double max
= maximum
;
618 for (i
= 1; i
< bucket_count
; ++i
) {
619 double linear_range
=
620 (min
* (bucket_count
-1 - i
) + max
* (i
- 1)) / (bucket_count
- 2);
621 ranges
->set_range(i
, static_cast<Sample
>(linear_range
+ 0.5));
623 ranges
->set_range(ranges
->size() - 1, HistogramBase::kSampleType_MAX
);
624 ranges
->ResetChecksum();
628 HistogramBase
* LinearHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
629 string histogram_name
;
634 uint32 range_checksum
;
636 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
637 &declared_max
, &bucket_count
, &range_checksum
)) {
641 HistogramBase
* histogram
= LinearHistogram::FactoryGet(
642 histogram_name
, declared_min
, declared_max
, bucket_count
, flags
);
643 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
644 // The serialized histogram might be corrupted.
650 //------------------------------------------------------------------------------
651 // This section provides implementation for BooleanHistogram.
652 //------------------------------------------------------------------------------
654 HistogramBase
* BooleanHistogram::FactoryGet(const string
& name
, int32 flags
) {
655 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
657 // To avoid racy destruction at shutdown, the following will be leaked.
658 BucketRanges
* ranges
= new BucketRanges(4);
659 LinearHistogram::InitializeBucketRanges(1, 2, 3, ranges
);
660 const BucketRanges
* registered_ranges
=
661 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
663 BooleanHistogram
* tentative_histogram
=
664 new BooleanHistogram(name
, registered_ranges
);
666 tentative_histogram
->SetFlags(flags
);
668 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
671 DCHECK_EQ(BOOLEAN_HISTOGRAM
, histogram
->GetHistogramType());
675 HistogramType
BooleanHistogram::GetHistogramType() const {
676 return BOOLEAN_HISTOGRAM
;
679 BooleanHistogram::BooleanHistogram(const string
& name
,
680 const BucketRanges
* ranges
)
681 : LinearHistogram(name
, 1, 2, 3, ranges
) {}
683 HistogramBase
* BooleanHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
684 string histogram_name
;
689 uint32 range_checksum
;
691 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
692 &declared_max
, &bucket_count
, &range_checksum
)) {
696 HistogramBase
* histogram
= BooleanHistogram::FactoryGet(
697 histogram_name
, flags
);
698 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
699 // The serialized histogram might be corrupted.
705 //------------------------------------------------------------------------------
707 //------------------------------------------------------------------------------
709 HistogramBase
* CustomHistogram::FactoryGet(const string
& name
,
710 const vector
<Sample
>& custom_ranges
,
712 CHECK(ValidateCustomRanges(custom_ranges
));
714 HistogramBase
* histogram
= StatisticsRecorder::FindHistogram(name
);
716 BucketRanges
* ranges
= CreateBucketRangesFromCustomRanges(custom_ranges
);
717 const BucketRanges
* registered_ranges
=
718 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges
);
720 // To avoid racy destruction at shutdown, the following will be leaked.
721 CustomHistogram
* tentative_histogram
=
722 new CustomHistogram(name
, registered_ranges
);
724 tentative_histogram
->SetFlags(flags
);
727 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram
);
730 DCHECK_EQ(histogram
->GetHistogramType(), CUSTOM_HISTOGRAM
);
734 HistogramType
CustomHistogram::GetHistogramType() const {
735 return CUSTOM_HISTOGRAM
;
739 vector
<Sample
> CustomHistogram::ArrayToCustomRanges(
740 const Sample
* values
, size_t num_values
) {
741 vector
<Sample
> all_values
;
742 for (size_t i
= 0; i
< num_values
; ++i
) {
743 Sample value
= values
[i
];
744 all_values
.push_back(value
);
746 // Ensure that a guard bucket is added. If we end up with duplicate
747 // values, FactoryGet will take care of removing them.
748 all_values
.push_back(value
+ 1);
753 CustomHistogram::CustomHistogram(const string
& name
,
754 const BucketRanges
* ranges
)
757 ranges
->range(ranges
->size() - 2),
761 bool CustomHistogram::SerializeInfoImpl(Pickle
* pickle
) const {
762 if (!Histogram::SerializeInfoImpl(pickle
))
765 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
767 for (size_t i
= 1; i
< bucket_ranges()->size() - 1; ++i
) {
768 if (!pickle
->WriteInt(bucket_ranges()->range(i
)))
774 double CustomHistogram::GetBucketSize(Count current
, size_t i
) const {
779 HistogramBase
* CustomHistogram::DeserializeInfoImpl(PickleIterator
* iter
) {
780 string histogram_name
;
785 uint32 range_checksum
;
787 if (!ReadHistogramArguments(iter
, &histogram_name
, &flags
, &declared_min
,
788 &declared_max
, &bucket_count
, &range_checksum
)) {
792 // First and last ranges are not serialized.
793 vector
<Sample
> sample_ranges(bucket_count
- 1);
795 for (size_t i
= 0; i
< sample_ranges
.size(); ++i
) {
796 if (!iter
->ReadInt(&sample_ranges
[i
]))
800 HistogramBase
* histogram
= CustomHistogram::FactoryGet(
801 histogram_name
, sample_ranges
, flags
);
802 if (!ValidateRangeChecksum(*histogram
, range_checksum
)) {
803 // The serialized histogram might be corrupted.
810 bool CustomHistogram::ValidateCustomRanges(
811 const vector
<Sample
>& custom_ranges
) {
812 bool has_valid_range
= false;
813 for (size_t i
= 0; i
< custom_ranges
.size(); i
++) {
814 Sample sample
= custom_ranges
[i
];
815 if (sample
< 0 || sample
> HistogramBase::kSampleType_MAX
- 1)
818 has_valid_range
= true;
820 return has_valid_range
;
824 BucketRanges
* CustomHistogram::CreateBucketRangesFromCustomRanges(
825 const vector
<Sample
>& custom_ranges
) {
826 // Remove the duplicates in the custom ranges array.
827 vector
<int> ranges
= custom_ranges
;
828 ranges
.push_back(0); // Ensure we have a zero value.
829 ranges
.push_back(HistogramBase::kSampleType_MAX
);
830 std::sort(ranges
.begin(), ranges
.end());
831 ranges
.erase(std::unique(ranges
.begin(), ranges
.end()), ranges
.end());
833 BucketRanges
* bucket_ranges
= new BucketRanges(ranges
.size());
834 for (size_t i
= 0; i
< ranges
.size(); i
++) {
835 bucket_ranges
->set_range(i
, ranges
[i
]);
837 bucket_ranges
->ResetChecksum();
838 return bucket_ranges
;