michael@0: // Copyright (c) 2011 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // Histogram is an object that aggregates statistics, and can summarize them in michael@0: // various forms, including ASCII graphical, HTML, and numerically (as a michael@0: // vector of numbers corresponding to each of the aggregating buckets). michael@0: // See header file for details and examples. michael@0: michael@0: #include "base/histogram.h" michael@0: michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: michael@0: #include "base/logging.h" michael@0: #include "base/pickle.h" michael@0: #include "base/string_util.h" michael@0: #include "base/logging.h" michael@0: michael@0: namespace base { michael@0: michael@0: #define DVLOG(x) CHROMIUM_LOG(ERROR) michael@0: #define CHECK_GT DCHECK_GT michael@0: #define CHECK_LT DCHECK_LT michael@0: typedef ::Lock Lock; michael@0: typedef ::AutoLock AutoLock; michael@0: michael@0: // Static table of checksums for all possible 8 bit bytes. michael@0: const uint32_t Histogram::kCrcTable[256] = {0x0, 0x77073096L, 0xee0e612cL, michael@0: 0x990951baL, 0x76dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0xedb8832L, michael@0: 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x9b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, michael@0: 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, michael@0: 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, michael@0: 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, michael@0: 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, michael@0: 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, michael@0: 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, michael@0: 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, michael@0: 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, michael@0: 0xb6662d3dL, 0x76dc4190L, 0x1db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, michael@0: 0x6b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0xf00f934L, 0x9609a88eL, michael@0: 0xe10e9818L, 0x7f6a0dbbL, 0x86d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, michael@0: 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, michael@0: 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, michael@0: 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, michael@0: 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, michael@0: 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, michael@0: 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, michael@0: 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, michael@0: 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, michael@0: 0x9abfb3b6L, 0x3b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x4db2615L, michael@0: 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0xd6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, michael@0: 0x9309ff9dL, 0xa00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, michael@0: 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, michael@0: 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, michael@0: 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, michael@0: 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, michael@0: 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, michael@0: 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, michael@0: 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, michael@0: 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, michael@0: 0x26d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x5005713L, 0x95bf4a82L, michael@0: 0xe2b87a14L, 0x7bb12baeL, 0xcb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, michael@0: 0xbdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, michael@0: 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, michael@0: 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, michael@0: 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, michael@0: 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, michael@0: 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, michael@0: 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, michael@0: 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, michael@0: 0x2d02ef8dL, michael@0: }; michael@0: michael@0: typedef Histogram::Count Count; michael@0: michael@0: // static michael@0: const size_t Histogram::kBucketCount_MAX = 16384u; michael@0: michael@0: Histogram* Histogram::FactoryGet(const std::string& name, michael@0: Sample minimum, michael@0: Sample maximum, michael@0: size_t bucket_count, michael@0: Flags flags) { michael@0: Histogram* histogram(NULL); michael@0: michael@0: // Defensive code. michael@0: if (minimum < 1) michael@0: minimum = 1; michael@0: if (maximum > kSampleType_MAX - 1) michael@0: maximum = kSampleType_MAX - 1; michael@0: michael@0: if (!StatisticsRecorder::FindHistogram(name, &histogram)) { michael@0: // Extra variable is not needed... but this keeps this section basically michael@0: // identical to other derived classes in this file (and compiler will michael@0: // optimize away the extra variable. michael@0: Histogram* tentative_histogram = michael@0: new Histogram(name, minimum, maximum, bucket_count); michael@0: tentative_histogram->InitializeBucketRange(); michael@0: tentative_histogram->SetFlags(flags); michael@0: histogram = michael@0: StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram); michael@0: } michael@0: michael@0: DCHECK_EQ(HISTOGRAM, histogram->histogram_type()); michael@0: DCHECK(histogram->HasConstructorArguments(minimum, maximum, bucket_count)); michael@0: return histogram; michael@0: } michael@0: michael@0: Histogram* Histogram::FactoryTimeGet(const std::string& name, michael@0: TimeDelta minimum, michael@0: TimeDelta maximum, michael@0: size_t bucket_count, michael@0: Flags flags) { michael@0: return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(), michael@0: bucket_count, flags); michael@0: } michael@0: michael@0: void Histogram::Add(int value) { michael@0: if (value > kSampleType_MAX - 1) michael@0: value = kSampleType_MAX - 1; michael@0: if (value < 0) michael@0: value = 0; michael@0: size_t index = BucketIndex(value); michael@0: DCHECK_GE(value, ranges(index)); michael@0: DCHECK_LT(value, ranges(index + 1)); michael@0: Accumulate(value, 1, index); michael@0: } michael@0: michael@0: void Histogram::Subtract(int value) { michael@0: if (value > kSampleType_MAX - 1) michael@0: value = kSampleType_MAX - 1; michael@0: if (value < 0) michael@0: value = 0; michael@0: size_t index = BucketIndex(value); michael@0: DCHECK_GE(value, ranges(index)); michael@0: DCHECK_LT(value, ranges(index + 1)); michael@0: Accumulate(value, -1, index); michael@0: } michael@0: michael@0: void Histogram::AddBoolean(bool value) { michael@0: DCHECK(false); michael@0: } michael@0: michael@0: void Histogram::AddSampleSet(const SampleSet& sample) { michael@0: sample_.Add(sample); michael@0: } michael@0: michael@0: void Histogram::Clear() { michael@0: SampleSet ss; michael@0: ss.Resize(*this); michael@0: sample_ = ss; michael@0: } michael@0: michael@0: void Histogram::SetRangeDescriptions(const DescriptionPair descriptions[]) { michael@0: DCHECK(false); michael@0: } michael@0: michael@0: // The following methods provide a graphical histogram display. michael@0: void Histogram::WriteHTMLGraph(std::string* output) const { michael@0: // TBD(jar) Write a nice HTML bar chart, with divs an mouse-overs etc. michael@0: output->append("
");
michael@0:   WriteAscii(true, "
", output); michael@0: output->append("
"); michael@0: } michael@0: michael@0: void Histogram::WriteAscii(bool graph_it, const std::string& newline, michael@0: std::string* output) const { michael@0: // Get local (stack) copies of all effectively volatile class data so that we michael@0: // are consistent across our output activities. michael@0: SampleSet snapshot; michael@0: SnapshotSample(&snapshot); michael@0: Count sample_count = snapshot.TotalCount(); michael@0: michael@0: WriteAsciiHeader(snapshot, sample_count, output); michael@0: output->append(newline); michael@0: michael@0: // Prepare to normalize graphical rendering of bucket contents. michael@0: double max_size = 0; michael@0: if (graph_it) michael@0: max_size = GetPeakBucketSize(snapshot); michael@0: michael@0: // Calculate space needed to print bucket range numbers. Leave room to print michael@0: // nearly the largest bucket range without sliding over the histogram. michael@0: size_t largest_non_empty_bucket = bucket_count() - 1; michael@0: while (0 == snapshot.counts(largest_non_empty_bucket)) { michael@0: if (0 == largest_non_empty_bucket) michael@0: break; // All buckets are empty. michael@0: --largest_non_empty_bucket; michael@0: } michael@0: michael@0: // Calculate largest print width needed for any of our bucket range displays. michael@0: size_t print_width = 1; michael@0: for (size_t i = 0; i < bucket_count(); ++i) { michael@0: if (snapshot.counts(i)) { michael@0: size_t width = GetAsciiBucketRange(i).size() + 1; michael@0: if (width > print_width) michael@0: print_width = width; michael@0: } michael@0: } michael@0: michael@0: int64_t remaining = sample_count; michael@0: int64_t past = 0; michael@0: // Output the actual histogram graph. michael@0: for (size_t i = 0; i < bucket_count(); ++i) { michael@0: Count current = snapshot.counts(i); michael@0: if (!current && !PrintEmptyBucket(i)) michael@0: continue; michael@0: remaining -= current; michael@0: std::string range = GetAsciiBucketRange(i); michael@0: output->append(range); michael@0: for (size_t j = 0; range.size() + j < print_width + 1; ++j) michael@0: output->push_back(' '); michael@0: if (0 == current && i < bucket_count() - 1 && 0 == snapshot.counts(i + 1)) { michael@0: while (i < bucket_count() - 1 && 0 == snapshot.counts(i + 1)) michael@0: ++i; michael@0: output->append("... "); michael@0: output->append(newline); michael@0: continue; // No reason to plot emptiness. michael@0: } michael@0: double current_size = GetBucketSize(current, i); michael@0: if (graph_it) michael@0: WriteAsciiBucketGraph(current_size, max_size, output); michael@0: WriteAsciiBucketContext(past, current, remaining, i, output); michael@0: output->append(newline); michael@0: past += current; michael@0: } michael@0: DCHECK_EQ(sample_count, past); michael@0: } michael@0: michael@0: // static michael@0: std::string Histogram::SerializeHistogramInfo(const Histogram& histogram, michael@0: const SampleSet& snapshot) { michael@0: DCHECK_NE(NOT_VALID_IN_RENDERER, histogram.histogram_type()); michael@0: michael@0: Pickle pickle; michael@0: pickle.WriteString(histogram.histogram_name()); michael@0: pickle.WriteInt(histogram.declared_min()); michael@0: pickle.WriteInt(histogram.declared_max()); michael@0: pickle.WriteSize(histogram.bucket_count()); michael@0: pickle.WriteUInt32(histogram.range_checksum()); michael@0: pickle.WriteInt(histogram.histogram_type()); michael@0: pickle.WriteInt(histogram.flags()); michael@0: michael@0: snapshot.Serialize(&pickle); michael@0: return std::string(static_cast(pickle.data()), pickle.size()); michael@0: } michael@0: michael@0: // static michael@0: bool Histogram::DeserializeHistogramInfo(const std::string& histogram_info) { michael@0: if (histogram_info.empty()) { michael@0: return false; michael@0: } michael@0: michael@0: Pickle pickle(histogram_info.data(), michael@0: static_cast(histogram_info.size())); michael@0: std::string histogram_name; michael@0: int declared_min; michael@0: int declared_max; michael@0: size_t bucket_count; michael@0: uint32_t range_checksum; michael@0: int histogram_type; michael@0: int pickle_flags; michael@0: SampleSet sample; michael@0: michael@0: void* iter = NULL; michael@0: if (!pickle.ReadString(&iter, &histogram_name) || michael@0: !pickle.ReadInt(&iter, &declared_min) || michael@0: !pickle.ReadInt(&iter, &declared_max) || michael@0: !pickle.ReadSize(&iter, &bucket_count) || michael@0: !pickle.ReadUInt32(&iter, &range_checksum) || michael@0: !pickle.ReadInt(&iter, &histogram_type) || michael@0: !pickle.ReadInt(&iter, &pickle_flags) || michael@0: !sample.Histogram::SampleSet::Deserialize(&iter, pickle)) { michael@0: CHROMIUM_LOG(ERROR) << "Pickle error decoding Histogram: " << histogram_name; michael@0: return false; michael@0: } michael@0: DCHECK(pickle_flags & kIPCSerializationSourceFlag); michael@0: // Since these fields may have come from an untrusted renderer, do additional michael@0: // checks above and beyond those in Histogram::Initialize() michael@0: if (declared_max <= 0 || declared_min <= 0 || declared_max < declared_min || michael@0: INT_MAX / sizeof(Count) <= bucket_count || bucket_count < 2) { michael@0: CHROMIUM_LOG(ERROR) << "Values error decoding Histogram: " << histogram_name; michael@0: return false; michael@0: } michael@0: michael@0: Flags flags = static_cast(pickle_flags & ~kIPCSerializationSourceFlag); michael@0: michael@0: DCHECK_NE(NOT_VALID_IN_RENDERER, histogram_type); michael@0: michael@0: Histogram* render_histogram(NULL); michael@0: michael@0: if (histogram_type == HISTOGRAM) { michael@0: render_histogram = Histogram::FactoryGet( michael@0: histogram_name, declared_min, declared_max, bucket_count, flags); michael@0: } else if (histogram_type == LINEAR_HISTOGRAM) { michael@0: render_histogram = LinearHistogram::FactoryGet( michael@0: histogram_name, declared_min, declared_max, bucket_count, flags); michael@0: } else if (histogram_type == BOOLEAN_HISTOGRAM) { michael@0: render_histogram = BooleanHistogram::FactoryGet(histogram_name, flags); michael@0: } else { michael@0: CHROMIUM_LOG(ERROR) << "Error Deserializing Histogram Unknown histogram_type: " michael@0: << histogram_type; michael@0: return false; michael@0: } michael@0: michael@0: DCHECK_EQ(render_histogram->declared_min(), declared_min); michael@0: DCHECK_EQ(render_histogram->declared_max(), declared_max); michael@0: DCHECK_EQ(render_histogram->bucket_count(), bucket_count); michael@0: DCHECK_EQ(render_histogram->range_checksum(), range_checksum); michael@0: DCHECK_EQ(render_histogram->histogram_type(), histogram_type); michael@0: michael@0: if (render_histogram->flags() & kIPCSerializationSourceFlag) { michael@0: DVLOG(1) << "Single process mode, histogram observed and not copied: " michael@0: << histogram_name; michael@0: } else { michael@0: DCHECK_EQ(flags & render_histogram->flags(), flags); michael@0: render_histogram->AddSampleSet(sample); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // Methods for the validating a sample and a related histogram. michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: Histogram::Inconsistencies Histogram::FindCorruption( michael@0: const SampleSet& snapshot) const { michael@0: int inconsistencies = NO_INCONSISTENCIES; michael@0: Sample previous_range = -1; // Bottom range is always 0. michael@0: int64_t count = 0; michael@0: for (size_t index = 0; index < bucket_count(); ++index) { michael@0: count += snapshot.counts(index); michael@0: int new_range = ranges(index); michael@0: if (previous_range >= new_range) michael@0: inconsistencies |= BUCKET_ORDER_ERROR; michael@0: previous_range = new_range; michael@0: } michael@0: michael@0: if (!HasValidRangeChecksum()) michael@0: inconsistencies |= RANGE_CHECKSUM_ERROR; michael@0: michael@0: int64_t delta64 = snapshot.redundant_count() - count; michael@0: if (delta64 != 0) { michael@0: int delta = static_cast(delta64); michael@0: if (delta != delta64) michael@0: delta = INT_MAX; // Flag all giant errors as INT_MAX. michael@0: // Since snapshots of histograms are taken asynchronously relative to michael@0: // sampling (and snapped from different threads), it is pretty likely that michael@0: // we'll catch a redundant count that doesn't match the sample count. We michael@0: // allow for a certain amount of slop before flagging this as an michael@0: // inconsistency. Even with an inconsistency, we'll snapshot it again (for michael@0: // UMA in about a half hour, so we'll eventually get the data, if it was michael@0: // not the result of a corruption. If histograms show that 1 is "too tight" michael@0: // then we may try to use 2 or 3 for this slop value. michael@0: const int kCommonRaceBasedCountMismatch = 1; michael@0: if (delta > 0) { michael@0: UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountHigh", delta); michael@0: if (delta > kCommonRaceBasedCountMismatch) michael@0: inconsistencies |= COUNT_HIGH_ERROR; michael@0: } else { michael@0: DCHECK_GT(0, delta); michael@0: UMA_HISTOGRAM_COUNTS("Histogram.InconsistentCountLow", -delta); michael@0: if (-delta > kCommonRaceBasedCountMismatch) michael@0: inconsistencies |= COUNT_LOW_ERROR; michael@0: } michael@0: } michael@0: return static_cast(inconsistencies); michael@0: } michael@0: michael@0: Histogram::ClassType Histogram::histogram_type() const { michael@0: return HISTOGRAM; michael@0: } michael@0: michael@0: Histogram::Sample Histogram::ranges(size_t i) const { michael@0: return ranges_[i]; michael@0: } michael@0: michael@0: size_t Histogram::bucket_count() const { michael@0: return bucket_count_; michael@0: } michael@0: michael@0: // Do a safe atomic snapshot of sample data. michael@0: // This implementation assumes we are on a safe single thread. michael@0: void Histogram::SnapshotSample(SampleSet* sample) const { michael@0: // Note locking not done in this version!!! michael@0: *sample = sample_; michael@0: } michael@0: michael@0: bool Histogram::HasConstructorArguments(Sample minimum, michael@0: Sample maximum, michael@0: size_t bucket_count) { michael@0: return ((minimum == declared_min_) && (maximum == declared_max_) && michael@0: (bucket_count == bucket_count_)); michael@0: } michael@0: michael@0: bool Histogram::HasConstructorTimeDeltaArguments(TimeDelta minimum, michael@0: TimeDelta maximum, michael@0: size_t bucket_count) { michael@0: return ((minimum.InMilliseconds() == declared_min_) && michael@0: (maximum.InMilliseconds() == declared_max_) && michael@0: (bucket_count == bucket_count_)); michael@0: } michael@0: michael@0: bool Histogram::HasValidRangeChecksum() const { michael@0: return CalculateRangeChecksum() == range_checksum_; michael@0: } michael@0: michael@0: size_t Histogram::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) michael@0: { michael@0: size_t n = 0; michael@0: n += aMallocSizeOf(this); michael@0: // We're not allowed to do deep dives into STL data structures. This michael@0: // is as close as we can get to measuring this array. michael@0: n += aMallocSizeOf(&ranges_[0]); michael@0: n += sample_.SizeOfExcludingThis(aMallocSizeOf); michael@0: return n; michael@0: } michael@0: michael@0: size_t Histogram::SampleSet::SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) michael@0: { michael@0: // We're not allowed to do deep dives into STL data structures. This michael@0: // is as close as we can get to measuring this array. michael@0: return aMallocSizeOf(&counts_[0]); michael@0: } michael@0: michael@0: Histogram::Histogram(const std::string& name, Sample minimum, michael@0: Sample maximum, size_t bucket_count) michael@0: : sample_(), michael@0: histogram_name_(name), michael@0: declared_min_(minimum), michael@0: declared_max_(maximum), michael@0: bucket_count_(bucket_count), michael@0: flags_(kNoFlags), michael@0: ranges_(bucket_count + 1, 0), michael@0: range_checksum_(0) { michael@0: Initialize(); michael@0: } michael@0: michael@0: Histogram::Histogram(const std::string& name, TimeDelta minimum, michael@0: TimeDelta maximum, size_t bucket_count) michael@0: : sample_(), michael@0: histogram_name_(name), michael@0: declared_min_(static_cast (minimum.InMilliseconds())), michael@0: declared_max_(static_cast (maximum.InMilliseconds())), michael@0: bucket_count_(bucket_count), michael@0: flags_(kNoFlags), michael@0: ranges_(bucket_count + 1, 0), michael@0: range_checksum_(0) { michael@0: Initialize(); michael@0: } michael@0: michael@0: Histogram::~Histogram() { michael@0: if (StatisticsRecorder::dump_on_exit()) { michael@0: std::string output; michael@0: WriteAscii(true, "\n", &output); michael@0: CHROMIUM_LOG(INFO) << output; michael@0: } michael@0: michael@0: // Just to make sure most derived class did this properly... michael@0: DCHECK(ValidateBucketRanges()); michael@0: } michael@0: michael@0: // Calculate what range of values are held in each bucket. michael@0: // We have to be careful that we don't pick a ratio between starting points in michael@0: // consecutive buckets that is sooo small, that the integer bounds are the same michael@0: // (effectively making one bucket get no values). We need to avoid: michael@0: // ranges_[i] == ranges_[i + 1] michael@0: // To avoid that, we just do a fine-grained bucket width as far as we need to michael@0: // until we get a ratio that moves us along at least 2 units at a time. From michael@0: // that bucket onward we do use the exponential growth of buckets. michael@0: void Histogram::InitializeBucketRange() { michael@0: double log_max = log(static_cast(declared_max())); michael@0: double log_ratio; michael@0: double log_next; michael@0: size_t bucket_index = 1; michael@0: Sample current = declared_min(); michael@0: SetBucketRange(bucket_index, current); michael@0: while (bucket_count() > ++bucket_index) { michael@0: double log_current; michael@0: log_current = log(static_cast(current)); michael@0: // Calculate the count'th root of the range. michael@0: log_ratio = (log_max - log_current) / (bucket_count() - bucket_index); michael@0: // See where the next bucket would start. michael@0: log_next = log_current + log_ratio; michael@0: int next; michael@0: next = static_cast(floor(exp(log_next) + 0.5)); michael@0: if (next > current) michael@0: current = next; michael@0: else michael@0: ++current; // Just do a narrow bucket, and keep trying. michael@0: SetBucketRange(bucket_index, current); michael@0: } michael@0: ResetRangeChecksum(); michael@0: michael@0: DCHECK_EQ(bucket_count(), bucket_index); michael@0: } michael@0: michael@0: bool Histogram::PrintEmptyBucket(size_t index) const { michael@0: return true; michael@0: } michael@0: michael@0: size_t Histogram::BucketIndex(Sample value) const { michael@0: // Use simple binary search. This is very general, but there are better michael@0: // approaches if we knew that the buckets were linearly distributed. michael@0: DCHECK_LE(ranges(0), value); michael@0: DCHECK_GT(ranges(bucket_count()), value); michael@0: size_t under = 0; michael@0: size_t over = bucket_count(); michael@0: size_t mid; michael@0: michael@0: do { michael@0: DCHECK_GE(over, under); michael@0: mid = under + (over - under)/2; michael@0: if (mid == under) michael@0: break; michael@0: if (ranges(mid) <= value) michael@0: under = mid; michael@0: else michael@0: over = mid; michael@0: } while (true); michael@0: michael@0: DCHECK_LE(ranges(mid), value); michael@0: CHECK_GT(ranges(mid+1), value); michael@0: return mid; michael@0: } michael@0: michael@0: // Use the actual bucket widths (like a linear histogram) until the widths get michael@0: // over some transition value, and then use that transition width. Exponentials michael@0: // get so big so fast (and we don't expect to see a lot of entries in the large michael@0: // buckets), so we need this to make it possible to see what is going on and michael@0: // not have 0-graphical-height buckets. michael@0: double Histogram::GetBucketSize(Count current, size_t i) const { michael@0: DCHECK_GT(ranges(i + 1), ranges(i)); michael@0: static const double kTransitionWidth = 5; michael@0: double denominator = ranges(i + 1) - ranges(i); michael@0: if (denominator > kTransitionWidth) michael@0: denominator = kTransitionWidth; // Stop trying to normalize. michael@0: return current/denominator; michael@0: } michael@0: michael@0: void Histogram::ResetRangeChecksum() { michael@0: range_checksum_ = CalculateRangeChecksum(); michael@0: } michael@0: michael@0: const std::string Histogram::GetAsciiBucketRange(size_t i) const { michael@0: std::string result; michael@0: if (kHexRangePrintingFlag & flags_) michael@0: StringAppendF(&result, "%#x", ranges(i)); michael@0: else michael@0: StringAppendF(&result, "%d", ranges(i)); michael@0: return result; michael@0: } michael@0: michael@0: // Update histogram data with new sample. michael@0: void Histogram::Accumulate(Sample value, Count count, size_t index) { michael@0: // Note locking not done in this version!!! michael@0: sample_.AccumulateWithExponentialStats(value, count, index, michael@0: flags_ & kExtendedStatisticsFlag); michael@0: } michael@0: michael@0: void Histogram::SetBucketRange(size_t i, Sample value) { michael@0: DCHECK_GT(bucket_count_, i); michael@0: ranges_[i] = value; michael@0: } michael@0: michael@0: bool Histogram::ValidateBucketRanges() const { michael@0: // Standard assertions that all bucket ranges should satisfy. michael@0: DCHECK_EQ(bucket_count_ + 1, ranges_.size()); michael@0: DCHECK_EQ(0, ranges_[0]); michael@0: DCHECK_EQ(declared_min(), ranges_[1]); michael@0: DCHECK_EQ(declared_max(), ranges_[bucket_count_ - 1]); michael@0: DCHECK_EQ(kSampleType_MAX, ranges_[bucket_count_]); michael@0: return true; michael@0: } michael@0: michael@0: uint32_t Histogram::CalculateRangeChecksum() const { michael@0: DCHECK_EQ(ranges_.size(), bucket_count() + 1); michael@0: uint32_t checksum = static_cast(ranges_.size()); // Seed checksum. michael@0: for (size_t index = 0; index < bucket_count(); ++index) michael@0: checksum = Crc32(checksum, ranges(index)); michael@0: return checksum; michael@0: } michael@0: michael@0: void Histogram::Initialize() { michael@0: sample_.Resize(*this); michael@0: if (declared_min_ < 1) michael@0: declared_min_ = 1; michael@0: if (declared_max_ > kSampleType_MAX - 1) michael@0: declared_max_ = kSampleType_MAX - 1; michael@0: DCHECK_LE(declared_min_, declared_max_); michael@0: DCHECK_GT(bucket_count_, 1u); michael@0: CHECK_LT(bucket_count_, kBucketCount_MAX); michael@0: size_t maximal_bucket_count = declared_max_ - declared_min_ + 2; michael@0: DCHECK_LE(bucket_count_, maximal_bucket_count); michael@0: DCHECK_EQ(0, ranges_[0]); michael@0: ranges_[bucket_count_] = kSampleType_MAX; michael@0: } michael@0: michael@0: // We generate the CRC-32 using the low order bits to select whether to XOR in michael@0: // the reversed polynomial 0xedb88320L. This is nice and simple, and allows us michael@0: // to keep the quotient in a uint32_t. Since we're not concerned about the nature michael@0: // of corruptions (i.e., we don't care about bit sequencing, since we are michael@0: // handling memory changes, which are more grotesque) so we don't bother to michael@0: // get the CRC correct for big-endian vs little-ending calculations. All we michael@0: // need is a nice hash, that tends to depend on all the bits of the sample, with michael@0: // very little chance of changes in one place impacting changes in another michael@0: // place. michael@0: uint32_t Histogram::Crc32(uint32_t sum, Histogram::Sample range) { michael@0: const bool kUseRealCrc = true; // TODO(jar): Switch to false and watch stats. michael@0: if (kUseRealCrc) { michael@0: union { michael@0: Histogram::Sample range; michael@0: unsigned char bytes[sizeof(Histogram::Sample)]; michael@0: } converter; michael@0: converter.range = range; michael@0: for (size_t i = 0; i < sizeof(converter); ++i) michael@0: sum = kCrcTable[(sum & 0xff) ^ converter.bytes[i]] ^ (sum >> 8); michael@0: } else { michael@0: // Use hash techniques provided in ReallyFastHash, except we don't care michael@0: // about "avalanching" (which would worsten the hash, and add collisions), michael@0: // and we don't care about edge cases since we have an even number of bytes. michael@0: union { michael@0: Histogram::Sample range; michael@0: uint16_t ints[sizeof(Histogram::Sample) / 2]; michael@0: } converter; michael@0: DCHECK_EQ(sizeof(Histogram::Sample), sizeof(converter)); michael@0: converter.range = range; michael@0: sum += converter.ints[0]; michael@0: sum = (sum << 16) ^ sum ^ (static_cast(converter.ints[1]) << 11); michael@0: sum += sum >> 11; michael@0: } michael@0: return sum; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // Private methods michael@0: michael@0: double Histogram::GetPeakBucketSize(const SampleSet& snapshot) const { michael@0: double max = 0; michael@0: for (size_t i = 0; i < bucket_count() ; ++i) { michael@0: double current_size = GetBucketSize(snapshot.counts(i), i); michael@0: if (current_size > max) michael@0: max = current_size; michael@0: } michael@0: return max; michael@0: } michael@0: michael@0: void Histogram::WriteAsciiHeader(const SampleSet& snapshot, michael@0: Count sample_count, michael@0: std::string* output) const { michael@0: StringAppendF(output, michael@0: "Histogram: %s recorded %d samples", michael@0: histogram_name().c_str(), michael@0: sample_count); michael@0: if (0 == sample_count) { michael@0: DCHECK_EQ(snapshot.sum(), 0); michael@0: } else { michael@0: double average = static_cast(snapshot.sum()) / sample_count; michael@0: michael@0: StringAppendF(output, ", average = %.1f", average); michael@0: } michael@0: if (flags_ & ~kHexRangePrintingFlag) michael@0: StringAppendF(output, " (flags = 0x%x)", flags_ & ~kHexRangePrintingFlag); michael@0: } michael@0: michael@0: void Histogram::WriteAsciiBucketContext(const int64_t past, michael@0: const Count current, michael@0: const int64_t remaining, michael@0: const size_t i, michael@0: std::string* output) const { michael@0: double scaled_sum = (past + current + remaining) / 100.0; michael@0: WriteAsciiBucketValue(current, scaled_sum, output); michael@0: if (0 < i) { michael@0: double percentage = past / scaled_sum; michael@0: StringAppendF(output, " {%3.1f%%}", percentage); michael@0: } michael@0: } michael@0: michael@0: void Histogram::WriteAsciiBucketValue(Count current, double scaled_sum, michael@0: std::string* output) const { michael@0: StringAppendF(output, " (%d = %3.1f%%)", current, current/scaled_sum); michael@0: } michael@0: michael@0: void Histogram::WriteAsciiBucketGraph(double current_size, double max_size, michael@0: std::string* output) const { michael@0: const int k_line_length = 72; // Maximal horizontal width of graph. michael@0: int x_count = static_cast(k_line_length * (current_size / max_size) michael@0: + 0.5); michael@0: int x_remainder = k_line_length - x_count; michael@0: michael@0: while (0 < x_count--) michael@0: output->append("-"); michael@0: output->append("O"); michael@0: while (0 < x_remainder--) michael@0: output->append(" "); michael@0: } michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // Methods for the Histogram::SampleSet class michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: Histogram::SampleSet::SampleSet() michael@0: : counts_(), michael@0: sum_(0), michael@0: sum_squares_(0), michael@0: log_sum_(0), michael@0: log_sum_squares_(0), michael@0: redundant_count_(0) { michael@0: } michael@0: michael@0: Histogram::SampleSet::~SampleSet() { michael@0: } michael@0: michael@0: void Histogram::SampleSet::Resize(const Histogram& histogram) { michael@0: counts_.resize(histogram.bucket_count(), 0); michael@0: } michael@0: michael@0: void Histogram::SampleSet::CheckSize(const Histogram& histogram) const { michael@0: DCHECK_EQ(histogram.bucket_count(), counts_.size()); michael@0: } michael@0: michael@0: void Histogram::SampleSet::Accumulate(Sample value, Count count, michael@0: size_t index) { michael@0: DCHECK(count == 1 || count == -1); michael@0: counts_[index] += count; michael@0: redundant_count_ += count; michael@0: sum_ += static_cast(count) * value; michael@0: DCHECK_GE(counts_[index], 0); michael@0: DCHECK_GE(sum_, 0); michael@0: DCHECK_GE(redundant_count_, 0); michael@0: } michael@0: michael@0: void Histogram::SampleSet::AccumulateWithLinearStats(Sample value, michael@0: Count count, michael@0: size_t index) { michael@0: Accumulate(value, count, index); michael@0: sum_squares_ += static_cast(count) * value * value; michael@0: } michael@0: michael@0: void Histogram::SampleSet::AccumulateWithExponentialStats(Sample value, michael@0: Count count, michael@0: size_t index, michael@0: bool computeExtendedStatistics) { michael@0: Accumulate(value, count, index); michael@0: if (computeExtendedStatistics) { michael@0: DCHECK_GE(value, 0); michael@0: float value_log = logf(static_cast(value) + 1.0f); michael@0: log_sum_ += count * value_log; michael@0: log_sum_squares_ += count * value_log * value_log; michael@0: } michael@0: } michael@0: michael@0: Count Histogram::SampleSet::TotalCount() const { michael@0: Count total = 0; michael@0: for (Counts::const_iterator it = counts_.begin(); michael@0: it != counts_.end(); michael@0: ++it) { michael@0: total += *it; michael@0: } michael@0: return total; michael@0: } michael@0: michael@0: void Histogram::SampleSet::Add(const SampleSet& other) { michael@0: DCHECK_EQ(counts_.size(), other.counts_.size()); michael@0: sum_ += other.sum_; michael@0: sum_squares_ += other.sum_squares_; michael@0: log_sum_ += other.log_sum_; michael@0: log_sum_squares_ += other.log_sum_squares_; michael@0: redundant_count_ += other.redundant_count_; michael@0: for (size_t index = 0; index < counts_.size(); ++index) michael@0: counts_[index] += other.counts_[index]; michael@0: } michael@0: michael@0: void Histogram::SampleSet::Subtract(const SampleSet& other) { michael@0: DCHECK_EQ(counts_.size(), other.counts_.size()); michael@0: // Note: Race conditions in snapshotting a sum may lead to (temporary) michael@0: // negative values when snapshots are later combined (and deltas calculated). michael@0: // As a result, we don't currently CHCEK() for positive values. michael@0: sum_ -= other.sum_; michael@0: sum_squares_ -= other.sum_squares_; michael@0: log_sum_ -= other.log_sum_; michael@0: log_sum_squares_ -= other.log_sum_squares_; michael@0: redundant_count_ -= other.redundant_count_; michael@0: for (size_t index = 0; index < counts_.size(); ++index) { michael@0: counts_[index] -= other.counts_[index]; michael@0: DCHECK_GE(counts_[index], 0); michael@0: } michael@0: } michael@0: michael@0: bool Histogram::SampleSet::Serialize(Pickle* pickle) const { michael@0: pickle->WriteInt64(sum_); michael@0: pickle->WriteInt64(redundant_count_); michael@0: pickle->WriteSize(counts_.size()); michael@0: michael@0: for (size_t index = 0; index < counts_.size(); ++index) { michael@0: pickle->WriteInt(counts_[index]); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: bool Histogram::SampleSet::Deserialize(void** iter, const Pickle& pickle) { michael@0: DCHECK_EQ(counts_.size(), 0u); michael@0: DCHECK_EQ(sum_, 0); michael@0: DCHECK_EQ(redundant_count_, 0); michael@0: michael@0: size_t counts_size; michael@0: michael@0: if (!pickle.ReadInt64(iter, &sum_) || michael@0: !pickle.ReadInt64(iter, &redundant_count_) || michael@0: !pickle.ReadSize(iter, &counts_size)) { michael@0: return false; michael@0: } michael@0: michael@0: if (counts_size == 0) michael@0: return false; michael@0: michael@0: int count = 0; michael@0: for (size_t index = 0; index < counts_size; ++index) { michael@0: int i; michael@0: if (!pickle.ReadInt(iter, &i)) michael@0: return false; michael@0: counts_.push_back(i); michael@0: count += i; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // LinearHistogram: This histogram uses a traditional set of evenly spaced michael@0: // buckets. michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: LinearHistogram::~LinearHistogram() { michael@0: } michael@0: michael@0: Histogram* LinearHistogram::FactoryGet(const std::string& name, michael@0: Sample minimum, michael@0: Sample maximum, michael@0: size_t bucket_count, michael@0: Flags flags) { michael@0: Histogram* histogram(NULL); michael@0: michael@0: if (minimum < 1) michael@0: minimum = 1; michael@0: if (maximum > kSampleType_MAX - 1) michael@0: maximum = kSampleType_MAX - 1; michael@0: michael@0: if (!StatisticsRecorder::FindHistogram(name, &histogram)) { michael@0: LinearHistogram* tentative_histogram = michael@0: new LinearHistogram(name, minimum, maximum, bucket_count); michael@0: tentative_histogram->InitializeBucketRange(); michael@0: tentative_histogram->SetFlags(flags); michael@0: histogram = michael@0: StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram); michael@0: } michael@0: michael@0: DCHECK_EQ(LINEAR_HISTOGRAM, histogram->histogram_type()); michael@0: DCHECK(histogram->HasConstructorArguments(minimum, maximum, bucket_count)); michael@0: return histogram; michael@0: } michael@0: michael@0: Histogram* LinearHistogram::FactoryTimeGet(const std::string& name, michael@0: TimeDelta minimum, michael@0: TimeDelta maximum, michael@0: size_t bucket_count, michael@0: Flags flags) { michael@0: return FactoryGet(name, minimum.InMilliseconds(), maximum.InMilliseconds(), michael@0: bucket_count, flags); michael@0: } michael@0: michael@0: Histogram::ClassType LinearHistogram::histogram_type() const { michael@0: return LINEAR_HISTOGRAM; michael@0: } michael@0: michael@0: void LinearHistogram::Accumulate(Sample value, Count count, size_t index) { michael@0: sample_.AccumulateWithLinearStats(value, count, index); michael@0: } michael@0: michael@0: void LinearHistogram::SetRangeDescriptions( michael@0: const DescriptionPair descriptions[]) { michael@0: for (int i =0; descriptions[i].description; ++i) { michael@0: bucket_description_[descriptions[i].sample] = descriptions[i].description; michael@0: } michael@0: } michael@0: michael@0: LinearHistogram::LinearHistogram(const std::string& name, michael@0: Sample minimum, michael@0: Sample maximum, michael@0: size_t bucket_count) michael@0: : Histogram(name, minimum >= 1 ? minimum : 1, maximum, bucket_count) { michael@0: } michael@0: michael@0: LinearHistogram::LinearHistogram(const std::string& name, michael@0: TimeDelta minimum, michael@0: TimeDelta maximum, michael@0: size_t bucket_count) michael@0: : Histogram(name, minimum >= TimeDelta::FromMilliseconds(1) ? michael@0: minimum : TimeDelta::FromMilliseconds(1), michael@0: maximum, bucket_count) { michael@0: } michael@0: michael@0: void LinearHistogram::InitializeBucketRange() { michael@0: DCHECK_GT(declared_min(), 0); // 0 is the underflow bucket here. michael@0: double min = declared_min(); michael@0: double max = declared_max(); michael@0: size_t i; michael@0: for (i = 1; i < bucket_count(); ++i) { michael@0: double linear_range = (min * (bucket_count() -1 - i) + max * (i - 1)) / michael@0: (bucket_count() - 2); michael@0: SetBucketRange(i, static_cast (linear_range + 0.5)); michael@0: } michael@0: ResetRangeChecksum(); michael@0: } michael@0: michael@0: double LinearHistogram::GetBucketSize(Count current, size_t i) const { michael@0: DCHECK_GT(ranges(i + 1), ranges(i)); michael@0: // Adjacent buckets with different widths would have "surprisingly" many (few) michael@0: // samples in a histogram if we didn't normalize this way. michael@0: double denominator = ranges(i + 1) - ranges(i); michael@0: return current/denominator; michael@0: } michael@0: michael@0: const std::string LinearHistogram::GetAsciiBucketRange(size_t i) const { michael@0: int range = ranges(i); michael@0: BucketDescriptionMap::const_iterator it = bucket_description_.find(range); michael@0: if (it == bucket_description_.end()) michael@0: return Histogram::GetAsciiBucketRange(i); michael@0: return it->second; michael@0: } michael@0: michael@0: bool LinearHistogram::PrintEmptyBucket(size_t index) const { michael@0: return bucket_description_.find(ranges(index)) == bucket_description_.end(); michael@0: } michael@0: michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // This section provides implementation for BooleanHistogram. michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: Histogram* BooleanHistogram::FactoryGet(const std::string& name, Flags flags) { michael@0: Histogram* histogram(NULL); michael@0: michael@0: if (!StatisticsRecorder::FindHistogram(name, &histogram)) { michael@0: BooleanHistogram* tentative_histogram = new BooleanHistogram(name); michael@0: tentative_histogram->InitializeBucketRange(); michael@0: tentative_histogram->SetFlags(flags); michael@0: histogram = michael@0: StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram); michael@0: } michael@0: michael@0: DCHECK_EQ(BOOLEAN_HISTOGRAM, histogram->histogram_type()); michael@0: return histogram; michael@0: } michael@0: michael@0: Histogram::ClassType BooleanHistogram::histogram_type() const { michael@0: return BOOLEAN_HISTOGRAM; michael@0: } michael@0: michael@0: void BooleanHistogram::AddBoolean(bool value) { michael@0: Add(value ? 1 : 0); michael@0: } michael@0: michael@0: BooleanHistogram::BooleanHistogram(const std::string& name) michael@0: : LinearHistogram(name, 1, 2, 3) { michael@0: } michael@0: michael@0: void michael@0: BooleanHistogram::Accumulate(Sample value, Count count, size_t index) michael@0: { michael@0: // Callers will have computed index based on the non-booleanified value. michael@0: // So we need to adjust the index manually. michael@0: LinearHistogram::Accumulate(!!value, count, value ? 1 : 0); michael@0: } michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // FlagHistogram: michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: Histogram * michael@0: FlagHistogram::FactoryGet(const std::string &name, Flags flags) michael@0: { michael@0: Histogram *h(nullptr); michael@0: michael@0: if (!StatisticsRecorder::FindHistogram(name, &h)) { michael@0: FlagHistogram *fh = new FlagHistogram(name); michael@0: fh->InitializeBucketRange(); michael@0: fh->SetFlags(flags); michael@0: size_t zero_index = fh->BucketIndex(0); michael@0: fh->LinearHistogram::Accumulate(0, 1, zero_index); michael@0: h = StatisticsRecorder::RegisterOrDeleteDuplicate(fh); michael@0: } michael@0: michael@0: return h; michael@0: } michael@0: michael@0: FlagHistogram::FlagHistogram(const std::string &name) michael@0: : BooleanHistogram(name), mSwitched(false) { michael@0: } michael@0: michael@0: Histogram::ClassType michael@0: FlagHistogram::histogram_type() const michael@0: { michael@0: return FLAG_HISTOGRAM; michael@0: } michael@0: michael@0: void michael@0: FlagHistogram::Accumulate(Sample value, Count count, size_t index) michael@0: { michael@0: if (mSwitched) { michael@0: return; michael@0: } michael@0: michael@0: mSwitched = true; michael@0: DCHECK_EQ(value, 1); michael@0: LinearHistogram::Accumulate(value, 1, index); michael@0: size_t zero_index = BucketIndex(0); michael@0: LinearHistogram::Accumulate(0, -1, zero_index); michael@0: } michael@0: michael@0: void michael@0: FlagHistogram::AddSampleSet(const SampleSet& sample) { michael@0: DCHECK_EQ(bucket_count(), sample.size()); michael@0: // We can't be sure the SampleSet provided came from another FlagHistogram, michael@0: // so we take the following steps: michael@0: // - If our flag has already been set do nothing. michael@0: // - Set our flag if the following hold: michael@0: // - The sum of the counts in the provided SampleSet is 1. michael@0: // - The bucket index for that single value is the same as the index where we michael@0: // would place our set flag. michael@0: // - Otherwise, take no action. michael@0: michael@0: if (mSwitched) { michael@0: return; michael@0: } michael@0: michael@0: if (sample.sum() != 1) { michael@0: return; michael@0: } michael@0: michael@0: size_t one_index = BucketIndex(1); michael@0: if (sample.counts(one_index) == 1) { michael@0: Accumulate(1, 1, one_index); michael@0: } michael@0: } michael@0: //------------------------------------------------------------------------------ michael@0: // CustomHistogram: michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: Histogram* CustomHistogram::FactoryGet(const std::string& name, michael@0: const std::vector& custom_ranges, michael@0: Flags flags) { michael@0: Histogram* histogram(NULL); michael@0: michael@0: // Remove the duplicates in the custom ranges array. michael@0: std::vector ranges = custom_ranges; michael@0: ranges.push_back(0); // Ensure we have a zero value. michael@0: std::sort(ranges.begin(), ranges.end()); michael@0: ranges.erase(std::unique(ranges.begin(), ranges.end()), ranges.end()); michael@0: if (ranges.size() <= 1) { michael@0: DCHECK(false); michael@0: // Note that we pushed a 0 in above, so for defensive code.... michael@0: ranges.push_back(1); // Put in some data so we can index to [1]. michael@0: } michael@0: michael@0: DCHECK_LT(ranges.back(), kSampleType_MAX); michael@0: michael@0: if (!StatisticsRecorder::FindHistogram(name, &histogram)) { michael@0: CustomHistogram* tentative_histogram = new CustomHistogram(name, ranges); michael@0: tentative_histogram->InitializedCustomBucketRange(ranges); michael@0: tentative_histogram->SetFlags(flags); michael@0: histogram = michael@0: StatisticsRecorder::RegisterOrDeleteDuplicate(tentative_histogram); michael@0: } michael@0: michael@0: DCHECK_EQ(histogram->histogram_type(), CUSTOM_HISTOGRAM); michael@0: DCHECK(histogram->HasConstructorArguments(ranges[1], ranges.back(), michael@0: ranges.size())); michael@0: return histogram; michael@0: } michael@0: michael@0: Histogram::ClassType CustomHistogram::histogram_type() const { michael@0: return CUSTOM_HISTOGRAM; michael@0: } michael@0: michael@0: CustomHistogram::CustomHistogram(const std::string& name, michael@0: const std::vector& custom_ranges) michael@0: : Histogram(name, custom_ranges[1], custom_ranges.back(), michael@0: custom_ranges.size()) { michael@0: DCHECK_GT(custom_ranges.size(), 1u); michael@0: DCHECK_EQ(custom_ranges[0], 0); michael@0: } michael@0: michael@0: void CustomHistogram::InitializedCustomBucketRange( michael@0: const std::vector& custom_ranges) { michael@0: DCHECK_GT(custom_ranges.size(), 1u); michael@0: DCHECK_EQ(custom_ranges[0], 0); michael@0: DCHECK_LE(custom_ranges.size(), bucket_count()); michael@0: for (size_t index = 0; index < custom_ranges.size(); ++index) michael@0: SetBucketRange(index, custom_ranges[index]); michael@0: ResetRangeChecksum(); michael@0: } michael@0: michael@0: double CustomHistogram::GetBucketSize(Count current, size_t i) const { michael@0: return 1; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------------ michael@0: // The next section handles global (central) support for all histograms, as well michael@0: // as startup/teardown of this service. michael@0: //------------------------------------------------------------------------------ michael@0: michael@0: // This singleton instance should be started during the single threaded portion michael@0: // of main(), and hence it is not thread safe. It initializes globals to michael@0: // provide support for all future calls. michael@0: StatisticsRecorder::StatisticsRecorder() { michael@0: DCHECK(!histograms_); michael@0: if (lock_ == NULL) { michael@0: // This will leak on purpose. It's the only way to make sure we won't race michael@0: // against the static uninitialization of the module while one of our michael@0: // static methods relying on the lock get called at an inappropriate time michael@0: // during the termination phase. Since it's a static data member, we will michael@0: // leak one per process, which would be similar to the instance allocated michael@0: // during static initialization and released only on process termination. michael@0: lock_ = new base::Lock; michael@0: } michael@0: base::AutoLock auto_lock(*lock_); michael@0: histograms_ = new HistogramMap; michael@0: } michael@0: michael@0: StatisticsRecorder::~StatisticsRecorder() { michael@0: DCHECK(histograms_ && lock_); michael@0: michael@0: if (dump_on_exit_) { michael@0: std::string output; michael@0: WriteGraph("", &output); michael@0: CHROMIUM_LOG(INFO) << output; michael@0: } michael@0: // Clean up. michael@0: HistogramMap* histograms = NULL; michael@0: { michael@0: base::AutoLock auto_lock(*lock_); michael@0: histograms = histograms_; michael@0: histograms_ = NULL; michael@0: for (HistogramMap::iterator it = histograms->begin(); michael@0: histograms->end() != it; michael@0: ++it) { michael@0: // No other clients permanently hold Histogram references, so we michael@0: // have the only one and it is safe to delete it. michael@0: delete it->second; michael@0: } michael@0: } michael@0: delete histograms; michael@0: // We don't delete lock_ on purpose to avoid having to properly protect michael@0: // against it going away after we checked for NULL in the static methods. michael@0: } michael@0: michael@0: // static michael@0: bool StatisticsRecorder::IsActive() { michael@0: if (lock_ == NULL) michael@0: return false; michael@0: base::AutoLock auto_lock(*lock_); michael@0: return NULL != histograms_; michael@0: } michael@0: michael@0: Histogram* StatisticsRecorder::RegisterOrDeleteDuplicate(Histogram* histogram) { michael@0: DCHECK(histogram->HasValidRangeChecksum()); michael@0: if (lock_ == NULL) michael@0: return histogram; michael@0: base::AutoLock auto_lock(*lock_); michael@0: if (!histograms_) michael@0: return histogram; michael@0: const std::string name = histogram->histogram_name(); michael@0: HistogramMap::iterator it = histograms_->find(name); michael@0: // Avoid overwriting a previous registration. michael@0: if (histograms_->end() == it) { michael@0: (*histograms_)[name] = histogram; michael@0: } else { michael@0: delete histogram; // We already have one by this name. michael@0: histogram = it->second; michael@0: } michael@0: return histogram; michael@0: } michael@0: michael@0: // static michael@0: void StatisticsRecorder::WriteHTMLGraph(const std::string& query, michael@0: std::string* output) { michael@0: if (!IsActive()) michael@0: return; michael@0: output->append("About Histograms"); michael@0: if (!query.empty()) michael@0: output->append(" - " + query); michael@0: output->append("" michael@0: // We'd like the following no-cache... but it doesn't work. michael@0: // "" michael@0: ""); michael@0: michael@0: Histograms snapshot; michael@0: GetSnapshot(query, &snapshot); michael@0: for (Histograms::iterator it = snapshot.begin(); michael@0: it != snapshot.end(); michael@0: ++it) { michael@0: (*it)->WriteHTMLGraph(output); michael@0: output->append("


"); michael@0: } michael@0: output->append(""); michael@0: } michael@0: michael@0: // static michael@0: void StatisticsRecorder::WriteGraph(const std::string& query, michael@0: std::string* output) { michael@0: if (!IsActive()) michael@0: return; michael@0: if (query.length()) michael@0: StringAppendF(output, "Collections of histograms for %s\n", query.c_str()); michael@0: else michael@0: output->append("Collections of all histograms\n"); michael@0: michael@0: Histograms snapshot; michael@0: GetSnapshot(query, &snapshot); michael@0: for (Histograms::iterator it = snapshot.begin(); michael@0: it != snapshot.end(); michael@0: ++it) { michael@0: (*it)->WriteAscii(true, "\n", output); michael@0: output->append("\n"); michael@0: } michael@0: } michael@0: michael@0: // static michael@0: void StatisticsRecorder::GetHistograms(Histograms* output) { michael@0: if (lock_ == NULL) michael@0: return; michael@0: base::AutoLock auto_lock(*lock_); michael@0: if (!histograms_) michael@0: return; michael@0: for (HistogramMap::iterator it = histograms_->begin(); michael@0: histograms_->end() != it; michael@0: ++it) { michael@0: DCHECK_EQ(it->first, it->second->histogram_name()); michael@0: output->push_back(it->second); michael@0: } michael@0: } michael@0: michael@0: bool StatisticsRecorder::FindHistogram(const std::string& name, michael@0: Histogram** histogram) { michael@0: if (lock_ == NULL) michael@0: return false; michael@0: base::AutoLock auto_lock(*lock_); michael@0: if (!histograms_) michael@0: return false; michael@0: HistogramMap::iterator it = histograms_->find(name); michael@0: if (histograms_->end() == it) michael@0: return false; michael@0: *histogram = it->second; michael@0: return true; michael@0: } michael@0: michael@0: // private static michael@0: void StatisticsRecorder::GetSnapshot(const std::string& query, michael@0: Histograms* snapshot) { michael@0: if (lock_ == NULL) michael@0: return; michael@0: base::AutoLock auto_lock(*lock_); michael@0: if (!histograms_) michael@0: return; michael@0: for (HistogramMap::iterator it = histograms_->begin(); michael@0: histograms_->end() != it; michael@0: ++it) { michael@0: if (it->first.find(query) != std::string::npos) michael@0: snapshot->push_back(it->second); michael@0: } michael@0: } michael@0: michael@0: // static michael@0: StatisticsRecorder::HistogramMap* StatisticsRecorder::histograms_ = NULL; michael@0: // static michael@0: base::Lock* StatisticsRecorder::lock_ = NULL; michael@0: // static michael@0: bool StatisticsRecorder::dump_on_exit_ = false; michael@0: michael@0: } // namespace base