Histogram function to write tab-separated values.
[folly.git] / folly / Histogram.h
index 6b7cbcdd2af2d81ac3be18d2e25cd1c959044b1f..fb72145047558f86f0e0b694d79b4ee3ee3208a6 100644 (file)
 #define FOLLY_HISTOGRAM_H_
 
 #include <cstddef>
-#include <cstdint>
 #include <limits>
+#include <ostream>
 #include <string>
 #include <vector>
+#include <stdexcept>
+
+#include "folly/detail/Stats.h"
 
 namespace folly {
 
@@ -222,20 +225,7 @@ template <typename T>
 class Histogram {
  public:
   typedef T ValueType;
-
-  struct Bucket {
-    Bucket()
-      : sum(0),
-        count(0) {}
-
-    void clear() {
-      sum = 0;
-      count = 0;
-    }
-
-    ValueType sum;
-    uint64_t count;
-  };
+  typedef detail::Bucket<T> Bucket;
 
   Histogram(ValueType bucketSize, ValueType min, ValueType max)
     : buckets_(bucketSize, min, max, Bucket()) {}
@@ -269,6 +259,37 @@ class Histogram {
     }
   }
 
+  /* Merge two histogram data together */
+  void merge(Histogram &hist) {
+    // the two histogram bucket definitions must match to support
+    // a merge.
+    if (getBucketSize() != hist.getBucketSize() ||
+        getMin() != hist.getMin() ||
+        getMax() != hist.getMax() ||
+        getNumBuckets() != hist.getNumBuckets() ) {
+      throw std::invalid_argument("Cannot merge from input histogram.");
+    }
+
+    for (int i = 0; i < buckets_.getNumBuckets(); i++) {
+      buckets_.getByIndex(i) += hist.buckets_.getByIndex(i);
+    }
+  }
+
+  /* Copy bucket values from another histogram */
+  void copy(Histogram &hist) {
+    // the two histogram bucket definition must match
+    if (getBucketSize() != hist.getBucketSize() ||
+        getMin() != hist.getMin() ||
+        getMax() != hist.getMax() ||
+        getNumBuckets() != hist.getNumBuckets() ) {
+      throw std::invalid_argument("Cannot copy from input histogram.");
+    }
+
+    for (int i = 0; i < buckets_.getNumBuckets(); i++) {
+      buckets_.getByIndex(i) = hist.buckets_.getByIndex(i);
+    }
+  }
+
   /* Returns the bucket size of each bucket in the histogram. */
   ValueType getBucketSize() const {
     return buckets_.getBucketSize();
@@ -347,6 +368,12 @@ class Histogram {
    */
   std::string debugString() const;
 
+  /*
+   * Write the histogram contents in tab-separated values (TSV) format.
+   * Format is "min max count sum".
+   */
+  void toTSV(std::ostream& out, bool skipEmptyBuckets = true) const;
+
  private:
   struct CountFromBucket {
     uint64_t operator()(const Bucket& bucket) const {