blob: d5da3711409dc61002e4bc9e8efd5ee0f0fc24af [file] [log] [blame]
[email protected]a93721e22012-01-06 02:13:281// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
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.
9
[email protected]835d7c82010-10-14 04:38:3810#include "base/metrics/histogram.h"
initial.commitd7cae122008-07-26 21:49:3811
12#include <math.h>
[email protected]f1633932010-08-17 23:05:2813
14#include <algorithm>
initial.commitd7cae122008-07-26 21:49:3815#include <string>
16
[email protected]ec0c0aa2012-08-14 02:02:0017#include "base/compiler_specific.h"
18#include "base/debug/alias.h"
initial.commitd7cae122008-07-26 21:49:3819#include "base/logging.h"
[email protected]877ef562012-10-20 02:56:1820#include "base/metrics/sample_vector.h"
[email protected]567d30e2012-07-13 21:48:2921#include "base/metrics/statistics_recorder.h"
[email protected]3f383852009-04-03 18:18:5522#include "base/pickle.h"
[email protected]ec0c0aa2012-08-14 02:02:0023#include "base/string_util.h"
[email protected]f1633932010-08-17 23:05:2824#include "base/stringprintf.h"
[email protected]bc581a682011-01-01 23:16:2025#include "base/synchronization/lock.h"
[email protected]24a7ec52012-10-08 10:31:5026#include "base/values.h"
initial.commitd7cae122008-07-26 21:49:3827
[email protected]34d062322012-08-01 21:34:0828using std::string;
29using std::vector;
30
[email protected]835d7c82010-10-14 04:38:3831namespace base {
[email protected]e1acf6f2008-10-27 20:43:3332
[email protected]c50c21d2013-01-11 21:52:4433namespace {
34
35bool ReadHistogramArguments(PickleIterator* iter,
36 string* histogram_name,
37 int* flags,
38 int* declared_min,
39 int* declared_max,
40 uint64* bucket_count,
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;
49 return false;
50 }
51
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 ||
55 *declared_min <= 0 ||
56 *declared_max < *declared_min ||
57 INT_MAX / sizeof(HistogramBase::Count) <= *bucket_count ||
58 *bucket_count < 2) {
59 DLOG(ERROR) << "Values error decoding Histogram: " << histogram_name;
60 return false;
61 }
62
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;
67
68 return true;
69}
70
71bool ValidateRangeChecksum(const HistogramBase& histogram,
72 uint32 range_checksum) {
73 const Histogram& casted_histogram =
74 static_cast<const Histogram&>(histogram);
75
76 return casted_histogram.bucket_ranges()->checksum() == range_checksum;
77}
78
79} // namespace
80
[email protected]34d062322012-08-01 21:34:0881typedef HistogramBase::Count Count;
82typedef HistogramBase::Sample Sample;
initial.commitd7cae122008-07-26 21:49:3883
[email protected]b122c0c2011-02-23 22:31:1884// static
[email protected]9fce5f02011-03-02 08:04:5785const size_t Histogram::kBucketCount_MAX = 16384u;
[email protected]b122c0c2011-02-23 22:31:1886
[email protected]ec0c0aa2012-08-14 02:02:0087// TODO(rtenneti): delete this code after debugging.
[email protected]263a17a2012-08-16 03:03:5488void CheckCorruption(const Histogram& histogram, bool new_histogram) {
[email protected]ec0c0aa2012-08-14 02:02:0089 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);
95
[email protected]263a17a2012-08-16 03:03:5496 bool debug_new_histogram[1];
97 debug_new_histogram[0] = new_histogram;
98 base::debug::Alias(debug_new_histogram);
99
[email protected]ec0c0aa2012-08-14 02:02:00100 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);
[email protected]263a17a2012-08-16 03:03:54103 CHECK_LT(previous_range, new_range);
[email protected]ec0c0aa2012-08-14 02:02:00104 previous_range = new_range;
105 }
106
[email protected]263a17a2012-08-16 03:03:54107 CHECK(histogram.bucket_ranges()->HasValidChecksum());
[email protected]ec0c0aa2012-08-14 02:02:00108}
109
[email protected]34d062322012-08-01 21:34:08110Histogram* Histogram::FactoryGet(const string& name,
111 Sample minimum,
112 Sample maximum,
113 size_t bucket_count,
[email protected]7c7a42752012-08-09 05:14:15114 int32 flags) {
[email protected]e184be902012-08-07 04:49:24115 bool valid_arguments =
116 InspectConstructionArguments(name, &minimum, &maximum, &bucket_count);
117 DCHECK(valid_arguments);
[email protected]a93721e22012-01-06 02:13:28118
[email protected]993ae742012-07-18 18:06:30119 Histogram* histogram = StatisticsRecorder::FindHistogram(name);
120 if (!histogram) {
[email protected]81ce9f3b2011-04-05 04:48:53121 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08122 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
123 InitializeBucketRanges(minimum, maximum, bucket_count, ranges);
124 const BucketRanges* registered_ranges =
125 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
126
127 Histogram* tentative_histogram =
128 new Histogram(name, minimum, maximum, bucket_count, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54129 CheckCorruption(*tentative_histogram, true);
130
[email protected]81ce9f3b2011-04-05 04:48:53131 tentative_histogram->SetFlags(flags);
132 histogram =
133 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]e8829a192009-12-06 00:09:37134 }
[email protected]ec0c0aa2012-08-14 02:02:00135 // TODO(rtenneti): delete this code after debugging.
[email protected]263a17a2012-08-16 03:03:54136 CheckCorruption(*histogram, false);
[email protected]e8829a192009-12-06 00:09:37137
[email protected]07c02402012-10-31 06:20:25138 CHECK_EQ(HISTOGRAM, histogram->GetHistogramType());
[email protected]065d1702012-08-23 23:55:13139 CHECK(histogram->HasConstructionArguments(minimum, maximum, bucket_count));
[email protected]e8829a192009-12-06 00:09:37140 return histogram;
141}
142
[email protected]34d062322012-08-01 21:34:08143Histogram* Histogram::FactoryTimeGet(const string& name,
144 TimeDelta minimum,
145 TimeDelta maximum,
146 size_t bucket_count,
[email protected]7c7a42752012-08-09 05:14:15147 int32 flags) {
[email protected]34d062322012-08-01 21:34:08148 return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(),
149 bucket_count, flags);
150}
151
152TimeTicks Histogram::DebugNow() {
153#ifndef NDEBUG
154 return TimeTicks::Now();
155#else
156 return TimeTicks();
157#endif
158}
159
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.
168//
169// static
170void Histogram::InitializeBucketRanges(Sample minimum,
171 Sample maximum,
172 size_t bucket_count,
173 BucketRanges* ranges) {
174 DCHECK_EQ(ranges->size(), bucket_count + 1);
175 double log_max = log(static_cast<double>(maximum));
176 double log_ratio;
177 double log_next;
178 size_t bucket_index = 1;
179 Sample current = minimum;
180 ranges->set_range(bucket_index, current);
181 while (bucket_count > ++bucket_index) {
182 double log_current;
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;
188 Sample next;
189 next = static_cast<int>(floor(exp(log_next) + 0.5));
190 if (next > current)
191 current = next;
192 else
193 ++current; // Just do a narrow bucket, and keep trying.
194 ranges->set_range(bucket_index, current);
195 }
196 ranges->set_range(ranges->size() - 1, HistogramBase::kSampleType_MAX);
197 ranges->ResetChecksum();
198}
199
[email protected]34d062322012-08-01 21:34:08200void Histogram::AddBoolean(bool value) {
201 DCHECK(false);
202}
203
[email protected]2f7d9cd2012-09-22 03:42:12204// static
205const int Histogram::kCommonRaceBasedCountMismatch = 5;
[email protected]34d062322012-08-01 21:34:08206
[email protected]34d062322012-08-01 21:34:08207Histogram::Inconsistencies Histogram::FindCorruption(
[email protected]2f7d9cd2012-09-22 03:42:12208 const HistogramSamples& samples) const {
[email protected]34d062322012-08-01 21:34:08209 int inconsistencies = NO_INCONSISTENCIES;
210 Sample previous_range = -1; // Bottom range is always 0.
[email protected]34d062322012-08-01 21:34:08211 for (size_t index = 0; index < bucket_count(); ++index) {
[email protected]34d062322012-08-01 21:34:08212 int new_range = ranges(index);
213 if (previous_range >= new_range)
214 inconsistencies |= BUCKET_ORDER_ERROR;
215 previous_range = new_range;
216 }
217
218 if (!bucket_ranges()->HasValidChecksum())
219 inconsistencies |= RANGE_CHECKSUM_ERROR;
220
[email protected]2f7d9cd2012-09-22 03:42:12221 int64 delta64 = samples.redundant_count() - samples.TotalCount();
[email protected]34d062322012-08-01 21:34:08222 if (delta64 != 0) {
223 int delta = static_cast<int>(delta64);
224 if (delta != delta64)
225 delta = INT_MAX; // Flag all giant errors as INT_MAX.
[email protected]34d062322012-08-01 21:34:08226 if (delta > 0) {
227 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta);
228 if (delta > kCommonRaceBasedCountMismatch)
229 inconsistencies |= COUNT_HIGH_ERROR;
230 } else {
231 DCHECK_GT(0, delta);
232 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta);
233 if (-delta > kCommonRaceBasedCountMismatch)
234 inconsistencies |= COUNT_LOW_ERROR;
235 }
236 }
237 return static_cast<Inconsistencies>(inconsistencies);
238}
239
[email protected]34d062322012-08-01 21:34:08240Sample Histogram::ranges(size_t i) const {
241 return bucket_ranges_->range(i);
242}
243
244size_t Histogram::bucket_count() const {
245 return bucket_count_;
246}
247
[email protected]34d062322012-08-01 21:34:08248// static
249bool Histogram::InspectConstructionArguments(const string& name,
250 Sample* minimum,
251 Sample* maximum,
252 size_t* bucket_count) {
253 // Defensive code for backward compatibility.
254 if (*minimum < 1) {
[email protected]a5c7bd792012-08-02 00:29:04255 DVLOG(1) << "Histogram: " << name << " has bad minimum: " << *minimum;
[email protected]34d062322012-08-01 21:34:08256 *minimum = 1;
257 }
258 if (*maximum >= kSampleType_MAX) {
[email protected]a5c7bd792012-08-02 00:29:04259 DVLOG(1) << "Histogram: " << name << " has bad maximum: " << *maximum;
260 *maximum = kSampleType_MAX - 1;
[email protected]34d062322012-08-01 21:34:08261 }
[email protected]e184be902012-08-07 04:49:24262 if (*bucket_count >= kBucketCount_MAX) {
263 DVLOG(1) << "Histogram: " << name << " has bad bucket_count: "
264 << *bucket_count;
265 *bucket_count = kBucketCount_MAX - 1;
266 }
[email protected]34d062322012-08-01 21:34:08267
[email protected]e184be902012-08-07 04:49:24268 if (*minimum >= *maximum)
269 return false;
270 if (*bucket_count < 3)
[email protected]34d062322012-08-01 21:34:08271 return false;
272 if (*bucket_count > static_cast<size_t>(*maximum - *minimum + 2))
273 return false;
274 return true;
275}
276
[email protected]07c02402012-10-31 06:20:25277HistogramType Histogram::GetHistogramType() const {
278 return HISTOGRAM;
279}
280
[email protected]abae9b022012-10-24 08:18:52281bool Histogram::HasConstructionArguments(Sample minimum,
282 Sample maximum,
283 size_t bucket_count) const {
284 return ((minimum == declared_min_) && (maximum == declared_max_) &&
285 (bucket_count == bucket_count_));
286}
287
288void Histogram::Add(int value) {
289 DCHECK_EQ(0, ranges(0));
290 DCHECK_EQ(kSampleType_MAX, ranges(bucket_count_));
291
292 if (value > kSampleType_MAX - 1)
293 value = kSampleType_MAX - 1;
294 if (value < 0)
295 value = 0;
296 samples_->Accumulate(value, 1);
297}
298
299scoped_ptr<HistogramSamples> Histogram::SnapshotSamples() const {
300 return SnapshotSampleVector().PassAs<HistogramSamples>();
301}
302
[email protected]c50c21d2013-01-11 21:52:44303void Histogram::AddSamples(const HistogramSamples& samples) {
304 samples_->Add(samples);
305}
306
307bool Histogram::AddSamplesFromPickle(PickleIterator* iter) {
308 return samples_->AddFromPickle(iter);
309}
310
[email protected]abae9b022012-10-24 08:18:52311// The following methods provide a graphical histogram display.
312void Histogram::WriteHTMLGraph(string* output) const {
313 // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc.
314 output->append("<PRE>");
315 WriteAsciiImpl(true, "<br>", output);
316 output->append("</PRE>");
317}
318
319void Histogram::WriteAscii(string* output) const {
320 WriteAsciiImpl(true, "\n", output);
321}
322
[email protected]c50c21d2013-01-11 21:52:44323bool Histogram::SerializeInfoImpl(Pickle* pickle) const {
324 DCHECK(bucket_ranges()->HasValidChecksum());
325 return pickle->WriteString(histogram_name()) &&
326 pickle->WriteInt(flags()) &&
327 pickle->WriteInt(declared_min()) &&
328 pickle->WriteInt(declared_max()) &&
329 pickle->WriteUInt64(bucket_count()) &&
330 pickle->WriteUInt32(bucket_ranges()->checksum());
331}
332
[email protected]abae9b022012-10-24 08:18:52333Histogram::Histogram(const string& name,
334 Sample minimum,
335 Sample maximum,
336 size_t bucket_count,
337 const BucketRanges* ranges)
338 : HistogramBase(name),
339 bucket_ranges_(ranges),
340 declared_min_(minimum),
341 declared_max_(maximum),
342 bucket_count_(bucket_count) {
343 if (ranges)
344 samples_.reset(new SampleVector(ranges));
345}
346
347Histogram::~Histogram() {
348 if (StatisticsRecorder::dump_on_exit()) {
349 string output;
350 WriteAsciiImpl(true, "\n", &output);
351 DLOG(INFO) << output;
352 }
353}
354
[email protected]34d062322012-08-01 21:34:08355bool Histogram::PrintEmptyBucket(size_t index) const {
356 return true;
357}
358
[email protected]34d062322012-08-01 21:34:08359// Use the actual bucket widths (like a linear histogram) until the widths get
360// over some transition value, and then use that transition width. Exponentials
361// get so big so fast (and we don't expect to see a lot of entries in the large
362// buckets), so we need this to make it possible to see what is going on and
363// not have 0-graphical-height buckets.
364double Histogram::GetBucketSize(Count current, size_t i) const {
365 DCHECK_GT(ranges(i + 1), ranges(i));
366 static const double kTransitionWidth = 5;
367 double denominator = ranges(i + 1) - ranges(i);
368 if (denominator > kTransitionWidth)
369 denominator = kTransitionWidth; // Stop trying to normalize.
370 return current/denominator;
371}
372
373const string Histogram::GetAsciiBucketRange(size_t i) const {
374 string result;
[email protected]7c7a42752012-08-09 05:14:15375 if (kHexRangePrintingFlag & flags())
[email protected]34d062322012-08-01 21:34:08376 StringAppendF(&result, "%#x", ranges(i));
377 else
378 StringAppendF(&result, "%d", ranges(i));
379 return result;
380}
381
[email protected]34d062322012-08-01 21:34:08382//------------------------------------------------------------------------------
383// Private methods
384
[email protected]c50c21d2013-01-11 21:52:44385// static
386HistogramBase* Histogram::DeserializeInfoImpl(PickleIterator* iter) {
387 string histogram_name;
388 int flags;
389 int declared_min;
390 int declared_max;
391 uint64 bucket_count;
392 uint32 range_checksum;
393
394 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
395 &declared_max, &bucket_count, &range_checksum)) {
396 return NULL;
397 }
398
399 // Find or create the local version of the histogram in this process.
400 HistogramBase* histogram = Histogram::FactoryGet(
401 histogram_name, declared_min, declared_max, bucket_count, flags);
402
403 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
404 // The serialized histogram might be corrupted.
405 return NULL;
406 }
407 return histogram;
408}
409
[email protected]877ef562012-10-20 02:56:18410scoped_ptr<SampleVector> Histogram::SnapshotSampleVector() const {
411 scoped_ptr<SampleVector> samples(new SampleVector(bucket_ranges()));
412 samples->Add(*samples_);
413 return samples.Pass();
414}
415
[email protected]34d062322012-08-01 21:34:08416void Histogram::WriteAsciiImpl(bool graph_it,
417 const string& newline,
418 string* output) const {
419 // Get local (stack) copies of all effectively volatile class data so that we
420 // are consistent across our output activities.
[email protected]877ef562012-10-20 02:56:18421 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
[email protected]2f7d9cd2012-09-22 03:42:12422 Count sample_count = snapshot->TotalCount();
[email protected]34d062322012-08-01 21:34:08423
[email protected]2f7d9cd2012-09-22 03:42:12424 WriteAsciiHeader(*snapshot, sample_count, output);
[email protected]34d062322012-08-01 21:34:08425 output->append(newline);
426
427 // Prepare to normalize graphical rendering of bucket contents.
428 double max_size = 0;
429 if (graph_it)
[email protected]2f7d9cd2012-09-22 03:42:12430 max_size = GetPeakBucketSize(*snapshot);
[email protected]34d062322012-08-01 21:34:08431
432 // Calculate space needed to print bucket range numbers. Leave room to print
433 // nearly the largest bucket range without sliding over the histogram.
434 size_t largest_non_empty_bucket = bucket_count() - 1;
[email protected]2f7d9cd2012-09-22 03:42:12435 while (0 == snapshot->GetCountAtIndex(largest_non_empty_bucket)) {
[email protected]34d062322012-08-01 21:34:08436 if (0 == largest_non_empty_bucket)
437 break; // All buckets are empty.
438 --largest_non_empty_bucket;
439 }
440
441 // Calculate largest print width needed for any of our bucket range displays.
442 size_t print_width = 1;
443 for (size_t i = 0; i < bucket_count(); ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12444 if (snapshot->GetCountAtIndex(i)) {
[email protected]34d062322012-08-01 21:34:08445 size_t width = GetAsciiBucketRange(i).size() + 1;
446 if (width > print_width)
447 print_width = width;
448 }
449 }
450
451 int64 remaining = sample_count;
452 int64 past = 0;
453 // Output the actual histogram graph.
454 for (size_t i = 0; i < bucket_count(); ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12455 Count current = snapshot->GetCountAtIndex(i);
[email protected]34d062322012-08-01 21:34:08456 if (!current && !PrintEmptyBucket(i))
457 continue;
458 remaining -= current;
459 string range = GetAsciiBucketRange(i);
460 output->append(range);
461 for (size_t j = 0; range.size() + j < print_width + 1; ++j)
462 output->push_back(' ');
[email protected]2f7d9cd2012-09-22 03:42:12463 if (0 == current && i < bucket_count() - 1 &&
464 0 == snapshot->GetCountAtIndex(i + 1)) {
465 while (i < bucket_count() - 1 &&
466 0 == snapshot->GetCountAtIndex(i + 1)) {
[email protected]34d062322012-08-01 21:34:08467 ++i;
[email protected]2f7d9cd2012-09-22 03:42:12468 }
[email protected]34d062322012-08-01 21:34:08469 output->append("... ");
470 output->append(newline);
471 continue; // No reason to plot emptiness.
472 }
473 double current_size = GetBucketSize(current, i);
474 if (graph_it)
475 WriteAsciiBucketGraph(current_size, max_size, output);
476 WriteAsciiBucketContext(past, current, remaining, i, output);
477 output->append(newline);
478 past += current;
479 }
480 DCHECK_EQ(sample_count, past);
481}
482
[email protected]2f7d9cd2012-09-22 03:42:12483double Histogram::GetPeakBucketSize(const SampleVector& samples) const {
[email protected]34d062322012-08-01 21:34:08484 double max = 0;
485 for (size_t i = 0; i < bucket_count() ; ++i) {
[email protected]2f7d9cd2012-09-22 03:42:12486 double current_size = GetBucketSize(samples.GetCountAtIndex(i), i);
[email protected]34d062322012-08-01 21:34:08487 if (current_size > max)
488 max = current_size;
489 }
490 return max;
491}
492
[email protected]2f7d9cd2012-09-22 03:42:12493void Histogram::WriteAsciiHeader(const SampleVector& samples,
[email protected]34d062322012-08-01 21:34:08494 Count sample_count,
495 string* output) const {
496 StringAppendF(output,
497 "Histogram: %s recorded %d samples",
498 histogram_name().c_str(),
499 sample_count);
500 if (0 == sample_count) {
[email protected]2f7d9cd2012-09-22 03:42:12501 DCHECK_EQ(samples.sum(), 0);
[email protected]34d062322012-08-01 21:34:08502 } else {
[email protected]2f7d9cd2012-09-22 03:42:12503 double average = static_cast<float>(samples.sum()) / sample_count;
[email protected]34d062322012-08-01 21:34:08504
505 StringAppendF(output, ", average = %.1f", average);
506 }
[email protected]7c7a42752012-08-09 05:14:15507 if (flags() & ~kHexRangePrintingFlag)
508 StringAppendF(output, " (flags = 0x%x)", flags() & ~kHexRangePrintingFlag);
[email protected]34d062322012-08-01 21:34:08509}
510
511void Histogram::WriteAsciiBucketContext(const int64 past,
512 const Count current,
513 const int64 remaining,
514 const size_t i,
515 string* output) const {
516 double scaled_sum = (past + current + remaining) / 100.0;
517 WriteAsciiBucketValue(current, scaled_sum, output);
518 if (0 < i) {
519 double percentage = past / scaled_sum;
520 StringAppendF(output, " {%3.1f%%}", percentage);
521 }
522}
523
524void Histogram::WriteAsciiBucketValue(Count current,
525 double scaled_sum,
526 string* output) const {
527 StringAppendF(output, " (%d = %3.1f%%)", current, current/scaled_sum);
528}
529
530void Histogram::WriteAsciiBucketGraph(double current_size,
531 double max_size,
532 string* output) const {
533 const int k_line_length = 72; // Maximal horizontal width of graph.
534 int x_count = static_cast<int>(k_line_length * (current_size / max_size)
535 + 0.5);
536 int x_remainder = k_line_length - x_count;
537
538 while (0 < x_count--)
539 output->append("-");
540 output->append("O");
541 while (0 < x_remainder--)
542 output->append(" ");
543}
544
[email protected]24a7ec52012-10-08 10:31:50545void Histogram::GetParameters(DictionaryValue* params) const {
[email protected]07c02402012-10-31 06:20:25546 params->SetString("type", HistogramTypeToString(GetHistogramType()));
[email protected]24a7ec52012-10-08 10:31:50547 params->SetInteger("min", declared_min());
548 params->SetInteger("max", declared_max());
549 params->SetInteger("bucket_count", static_cast<int>(bucket_count()));
550}
551
552void Histogram::GetCountAndBucketData(Count* count, ListValue* buckets) const {
[email protected]877ef562012-10-20 02:56:18553 scoped_ptr<SampleVector> snapshot = SnapshotSampleVector();
[email protected]24a7ec52012-10-08 10:31:50554 *count = snapshot->TotalCount();
555 size_t index = 0;
556 for (size_t i = 0; i < bucket_count(); ++i) {
557 Sample count = snapshot->GetCountAtIndex(i);
558 if (count > 0) {
559 scoped_ptr<DictionaryValue> bucket_value(new DictionaryValue());
560 bucket_value->SetInteger("low", ranges(i));
561 if (i != bucket_count() - 1)
562 bucket_value->SetInteger("high", ranges(i + 1));
563 bucket_value->SetInteger("count", count);
564 buckets->Set(index, bucket_value.release());
565 ++index;
566 }
567 }
568}
569
[email protected]34d062322012-08-01 21:34:08570//------------------------------------------------------------------------------
571// LinearHistogram: This histogram uses a traditional set of evenly spaced
572// buckets.
573//------------------------------------------------------------------------------
574
575LinearHistogram::~LinearHistogram() {}
576
577Histogram* LinearHistogram::FactoryGet(const string& name,
578 Sample minimum,
579 Sample maximum,
580 size_t bucket_count,
[email protected]7c7a42752012-08-09 05:14:15581 int32 flags) {
[email protected]07c02402012-10-31 06:20:25582 return FactoryGetWithRangeDescription(
583 name, minimum, maximum, bucket_count, flags, NULL);
584}
585
586Histogram* LinearHistogram::FactoryTimeGet(const string& name,
587 TimeDelta minimum,
588 TimeDelta maximum,
589 size_t bucket_count,
590 int32 flags) {
591 return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(),
592 bucket_count, flags);
593}
594
595Histogram* LinearHistogram::FactoryGetWithRangeDescription(
596 const std::string& name,
597 Sample minimum,
598 Sample maximum,
599 size_t bucket_count,
600 int32 flags,
601 const DescriptionPair descriptions[]) {
[email protected]e184be902012-08-07 04:49:24602 bool valid_arguments = Histogram::InspectConstructionArguments(
603 name, &minimum, &maximum, &bucket_count);
604 DCHECK(valid_arguments);
[email protected]34d062322012-08-01 21:34:08605
606 Histogram* histogram = StatisticsRecorder::FindHistogram(name);
607 if (!histogram) {
608 // To avoid racy destruction at shutdown, the following will be leaked.
609 BucketRanges* ranges = new BucketRanges(bucket_count + 1);
610 InitializeBucketRanges(minimum, maximum, bucket_count, ranges);
611 const BucketRanges* registered_ranges =
612 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
613
614 LinearHistogram* tentative_histogram =
615 new LinearHistogram(name, minimum, maximum, bucket_count,
616 registered_ranges);
[email protected]263a17a2012-08-16 03:03:54617 CheckCorruption(*tentative_histogram, true);
618
[email protected]07c02402012-10-31 06:20:25619 // Set range descriptions.
620 if (descriptions) {
621 for (int i = 0; descriptions[i].description; ++i) {
622 tentative_histogram->bucket_description_[descriptions[i].sample] =
623 descriptions[i].description;
624 }
625 }
626
[email protected]34d062322012-08-01 21:34:08627 tentative_histogram->SetFlags(flags);
628 histogram =
629 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
630 }
[email protected]ec0c0aa2012-08-14 02:02:00631 // TODO(rtenneti): delete this code after debugging.
[email protected]263a17a2012-08-16 03:03:54632 CheckCorruption(*histogram, false);
[email protected]34d062322012-08-01 21:34:08633
[email protected]07c02402012-10-31 06:20:25634 CHECK_EQ(LINEAR_HISTOGRAM, histogram->GetHistogramType());
[email protected]065d1702012-08-23 23:55:13635 CHECK(histogram->HasConstructionArguments(minimum, maximum, bucket_count));
[email protected]34d062322012-08-01 21:34:08636 return histogram;
637}
638
[email protected]07c02402012-10-31 06:20:25639HistogramType LinearHistogram::GetHistogramType() const {
[email protected]b7d08202011-01-25 17:29:39640 return LINEAR_HISTOGRAM;
641}
642
[email protected]34d062322012-08-01 21:34:08643LinearHistogram::LinearHistogram(const string& name,
[email protected]835d7c82010-10-14 04:38:38644 Sample minimum,
645 Sample maximum,
[email protected]34d062322012-08-01 21:34:08646 size_t bucket_count,
647 const BucketRanges* ranges)
648 : Histogram(name, minimum, maximum, bucket_count, ranges) {
initial.commitd7cae122008-07-26 21:49:38649}
650
initial.commitd7cae122008-07-26 21:49:38651double LinearHistogram::GetBucketSize(Count current, size_t i) const {
[email protected]2ef3748f2010-10-19 17:33:28652 DCHECK_GT(ranges(i + 1), ranges(i));
initial.commitd7cae122008-07-26 21:49:38653 // Adjacent buckets with different widths would have "surprisingly" many (few)
654 // samples in a histogram if we didn't normalize this way.
655 double denominator = ranges(i + 1) - ranges(i);
656 return current/denominator;
657}
658
[email protected]34d062322012-08-01 21:34:08659const string LinearHistogram::GetAsciiBucketRange(size_t i) const {
[email protected]b7d08202011-01-25 17:29:39660 int range = ranges(i);
661 BucketDescriptionMap::const_iterator it = bucket_description_.find(range);
662 if (it == bucket_description_.end())
663 return Histogram::GetAsciiBucketRange(i);
664 return it->second;
665}
666
667bool LinearHistogram::PrintEmptyBucket(size_t index) const {
668 return bucket_description_.find(ranges(index)) == bucket_description_.end();
669}
670
[email protected]34d062322012-08-01 21:34:08671// static
672void LinearHistogram::InitializeBucketRanges(Sample minimum,
673 Sample maximum,
674 size_t bucket_count,
675 BucketRanges* ranges) {
676 DCHECK_EQ(ranges->size(), bucket_count + 1);
677 double min = minimum;
678 double max = maximum;
679 size_t i;
680 for (i = 1; i < bucket_count; ++i) {
681 double linear_range =
682 (min * (bucket_count -1 - i) + max * (i - 1)) / (bucket_count - 2);
683 ranges->set_range(i, static_cast<Sample>(linear_range + 0.5));
684 }
685 ranges->set_range(ranges->size() - 1, HistogramBase::kSampleType_MAX);
686 ranges->ResetChecksum();
687}
[email protected]b7d08202011-01-25 17:29:39688
[email protected]c50c21d2013-01-11 21:52:44689// static
690HistogramBase* LinearHistogram::DeserializeInfoImpl(PickleIterator* iter) {
691 string histogram_name;
692 int flags;
693 int declared_min;
694 int declared_max;
695 uint64 bucket_count;
696 uint32 range_checksum;
697
698 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
699 &declared_max, &bucket_count, &range_checksum)) {
700 return NULL;
701 }
702
703 HistogramBase* histogram = LinearHistogram::FactoryGet(
704 histogram_name, declared_min, declared_max, bucket_count, flags);
705 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
706 // The serialized histogram might be corrupted.
707 return NULL;
708 }
709 return histogram;
710}
711
initial.commitd7cae122008-07-26 21:49:38712//------------------------------------------------------------------------------
[email protected]e8829a192009-12-06 00:09:37713// This section provides implementation for BooleanHistogram.
714//------------------------------------------------------------------------------
715
[email protected]7c7a42752012-08-09 05:14:15716Histogram* BooleanHistogram::FactoryGet(const string& name, int32 flags) {
[email protected]993ae742012-07-18 18:06:30717 Histogram* histogram = StatisticsRecorder::FindHistogram(name);
718 if (!histogram) {
[email protected]81ce9f3b2011-04-05 04:48:53719 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08720 BucketRanges* ranges = new BucketRanges(4);
721 LinearHistogram::InitializeBucketRanges(1, 2, 3, ranges);
722 const BucketRanges* registered_ranges =
723 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
724
725 BooleanHistogram* tentative_histogram =
726 new BooleanHistogram(name, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54727 CheckCorruption(*tentative_histogram, true);
728
[email protected]81ce9f3b2011-04-05 04:48:53729 tentative_histogram->SetFlags(flags);
730 histogram =
731 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]e8829a192009-12-06 00:09:37732 }
[email protected]ec0c0aa2012-08-14 02:02:00733 // TODO(rtenneti): delete this code after debugging.
[email protected]263a17a2012-08-16 03:03:54734 CheckCorruption(*histogram, false);
[email protected]e8829a192009-12-06 00:09:37735
[email protected]07c02402012-10-31 06:20:25736 CHECK_EQ(BOOLEAN_HISTOGRAM, histogram->GetHistogramType());
[email protected]e8829a192009-12-06 00:09:37737 return histogram;
738}
739
[email protected]07c02402012-10-31 06:20:25740HistogramType BooleanHistogram::GetHistogramType() const {
[email protected]5d91c9e2010-07-28 17:25:28741 return BOOLEAN_HISTOGRAM;
742}
743
744void BooleanHistogram::AddBoolean(bool value) {
745 Add(value ? 1 : 0);
746}
747
[email protected]34d062322012-08-01 21:34:08748BooleanHistogram::BooleanHistogram(const string& name,
749 const BucketRanges* ranges)
750 : LinearHistogram(name, 1, 2, 3, ranges) {}
initial.commitd7cae122008-07-26 21:49:38751
[email protected]c50c21d2013-01-11 21:52:44752HistogramBase* BooleanHistogram::DeserializeInfoImpl(PickleIterator* iter) {
753 string histogram_name;
754 int flags;
755 int declared_min;
756 int declared_max;
757 uint64 bucket_count;
758 uint32 range_checksum;
759
760 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
761 &declared_max, &bucket_count, &range_checksum)) {
762 return NULL;
763 }
764
765 HistogramBase* histogram = BooleanHistogram::FactoryGet(
766 histogram_name, flags);
767 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
768 // The serialized histogram might be corrupted.
769 return NULL;
770 }
771 return histogram;
772}
773
initial.commitd7cae122008-07-26 21:49:38774//------------------------------------------------------------------------------
[email protected]70cc56e42010-04-29 22:39:55775// CustomHistogram:
776//------------------------------------------------------------------------------
777
[email protected]34d062322012-08-01 21:34:08778Histogram* CustomHistogram::FactoryGet(const string& name,
779 const vector<Sample>& custom_ranges,
[email protected]7c7a42752012-08-09 05:14:15780 int32 flags) {
[email protected]34d062322012-08-01 21:34:08781 CHECK(ValidateCustomRanges(custom_ranges));
[email protected]70cc56e42010-04-29 22:39:55782
[email protected]993ae742012-07-18 18:06:30783 Histogram* histogram = StatisticsRecorder::FindHistogram(name);
784 if (!histogram) {
[email protected]34d062322012-08-01 21:34:08785 BucketRanges* ranges = CreateBucketRangesFromCustomRanges(custom_ranges);
786 const BucketRanges* registered_ranges =
787 StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
788
[email protected]81ce9f3b2011-04-05 04:48:53789 // To avoid racy destruction at shutdown, the following will be leaked.
[email protected]34d062322012-08-01 21:34:08790 CustomHistogram* tentative_histogram =
791 new CustomHistogram(name, registered_ranges);
[email protected]263a17a2012-08-16 03:03:54792 CheckCorruption(*tentative_histogram, true);
793
[email protected]81ce9f3b2011-04-05 04:48:53794 tentative_histogram->SetFlags(flags);
[email protected]34d062322012-08-01 21:34:08795
[email protected]81ce9f3b2011-04-05 04:48:53796 histogram =
797 StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram);
[email protected]70cc56e42010-04-29 22:39:55798 }
[email protected]ec0c0aa2012-08-14 02:02:00799 // TODO(rtenneti): delete this code after debugging.
[email protected]263a17a2012-08-16 03:03:54800 CheckCorruption(*histogram, false);
[email protected]70cc56e42010-04-29 22:39:55801
[email protected]07c02402012-10-31 06:20:25802 CHECK_EQ(histogram->GetHistogramType(), CUSTOM_HISTOGRAM);
[email protected]70cc56e42010-04-29 22:39:55803 return histogram;
804}
805
[email protected]07c02402012-10-31 06:20:25806HistogramType CustomHistogram::GetHistogramType() const {
[email protected]5d91c9e2010-07-28 17:25:28807 return CUSTOM_HISTOGRAM;
808}
809
[email protected]961fefb2011-05-24 13:59:58810// static
[email protected]34d062322012-08-01 21:34:08811vector<Sample> CustomHistogram::ArrayToCustomRanges(
[email protected]961fefb2011-05-24 13:59:58812 const Sample* values, size_t num_values) {
[email protected]34d062322012-08-01 21:34:08813 vector<Sample> all_values;
[email protected]961fefb2011-05-24 13:59:58814 for (size_t i = 0; i < num_values; ++i) {
815 Sample value = values[i];
816 all_values.push_back(value);
817
818 // Ensure that a guard bucket is added. If we end up with duplicate
819 // values, FactoryGet will take care of removing them.
820 all_values.push_back(value + 1);
821 }
822 return all_values;
823}
824
[email protected]34d062322012-08-01 21:34:08825CustomHistogram::CustomHistogram(const string& name,
826 const BucketRanges* ranges)
827 : Histogram(name,
828 ranges->range(1),
829 ranges->range(ranges->size() - 2),
830 ranges->size() - 1,
831 ranges) {}
[email protected]70cc56e42010-04-29 22:39:55832
[email protected]c50c21d2013-01-11 21:52:44833bool CustomHistogram::SerializeInfoImpl(Pickle* pickle) const {
834 if (!Histogram::SerializeInfoImpl(pickle))
835 return false;
[email protected]cd56dff2011-11-13 04:19:15836
[email protected]c50c21d2013-01-11 21:52:44837 // Serialize ranges. First and last ranges are alwasy 0 and INT_MAX, so don't
838 // write them.
839 for (size_t i = 1; i < bucket_ranges()->size() - 1; ++i) {
840 if (!pickle->WriteInt(bucket_ranges()->range(i)))
[email protected]cd56dff2011-11-13 04:19:15841 return false;
842 }
843 return true;
844}
845
[email protected]70cc56e42010-04-29 22:39:55846double CustomHistogram::GetBucketSize(Count current, size_t i) const {
847 return 1;
848}
849
[email protected]34d062322012-08-01 21:34:08850// static
[email protected]c50c21d2013-01-11 21:52:44851HistogramBase* CustomHistogram::DeserializeInfoImpl(PickleIterator* iter) {
852 string histogram_name;
853 int flags;
854 int declared_min;
855 int declared_max;
856 uint64 bucket_count;
857 uint32 range_checksum;
858
859 if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
860 &declared_max, &bucket_count, &range_checksum)) {
861 return NULL;
862 }
863
864 // First and last ranges are not serialized.
865 vector<Sample> sample_ranges(bucket_count - 1);
866
867 for (size_t i = 0; i < sample_ranges.size(); ++i) {
868 if (!iter->ReadInt(&sample_ranges[i]))
869 return NULL;
870 }
871
872 HistogramBase* histogram = CustomHistogram::FactoryGet(
873 histogram_name, sample_ranges, flags);
874 if (!ValidateRangeChecksum(*histogram, range_checksum)) {
875 // The serialized histogram might be corrupted.
876 return NULL;
877 }
878 return histogram;
879}
880
881// static
[email protected]34d062322012-08-01 21:34:08882bool CustomHistogram::ValidateCustomRanges(
883 const vector<Sample>& custom_ranges) {
[email protected]640d95ef2012-08-04 06:23:03884 bool has_valid_range = false;
[email protected]34d062322012-08-01 21:34:08885 for (size_t i = 0; i < custom_ranges.size(); i++) {
[email protected]640d95ef2012-08-04 06:23:03886 Sample sample = custom_ranges[i];
887 if (sample < 0 || sample > HistogramBase::kSampleType_MAX - 1)
[email protected]34d062322012-08-01 21:34:08888 return false;
[email protected]640d95ef2012-08-04 06:23:03889 if (sample != 0)
890 has_valid_range = true;
[email protected]34d062322012-08-01 21:34:08891 }
[email protected]640d95ef2012-08-04 06:23:03892 return has_valid_range;
[email protected]34d062322012-08-01 21:34:08893}
894
895// static
896BucketRanges* CustomHistogram::CreateBucketRangesFromCustomRanges(
897 const vector<Sample>& custom_ranges) {
898 // Remove the duplicates in the custom ranges array.
899 vector<int> ranges = custom_ranges;
900 ranges.push_back(0); // Ensure we have a zero value.
901 ranges.push_back(HistogramBase::kSampleType_MAX);
902 std::sort(ranges.begin(), ranges.end());
903 ranges.erase(std::unique(ranges.begin(), ranges.end()), ranges.end());
904
905 BucketRanges* bucket_ranges = new BucketRanges(ranges.size());
906 for (size_t i = 0; i < ranges.size(); i++) {
907 bucket_ranges->set_range(i, ranges[i]);
908 }
909 bucket_ranges->ResetChecksum();
910 return bucket_ranges;
911}
912
[email protected]835d7c82010-10-14 04:38:38913} // namespace base