-
Notifications
You must be signed in to change notification settings - Fork 41
/
lib.rs
1892 lines (1710 loc) · 80.2 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! HdrSample is a port of Gil Tene's HdrHistogram to native Rust. It provides recording and
//! analyzing of sampled data value counts across a large, configurable value range with
//! configurable precision within the range. The resulting "HDR" histogram allows for fast and
//! accurate analysis of the extreme ranges of data with non-normal distributions, like latency.
//!
//! # HdrHistogram
//!
//! What follows is a description from [the HdrHistogram
//! website](https://hdrhistogram.github.io/HdrHistogram/). Users are encouraged to read the
//! documentation from the original [Java
//! implementation](https://github.com/HdrHistogram/HdrHistogram), as most of the concepts
//! translate directly to the Rust port.
//!
//! HdrHistogram supports the recording and analyzing of sampled data value counts across a
//! configurable integer value range with configurable value precision within the range. Value
//! precision is expressed as the number of significant digits in the value recording, and provides
//! control over value quantization behavior across the value range and the subsequent value
//! resolution at any given level.
//!
//! For example, a Histogram could be configured to track the counts of observed integer values
//! between 0 and 3,600,000,000 while maintaining a value precision of 3 significant digits across
//! that range. Value quantization within the range will thus be no larger than 1/1,000th (or 0.1%)
//! of any value. This example Histogram could be used to track and analyze the counts of observed
//! response times ranging between 1 microsecond and 1 hour in magnitude, while maintaining a value
//! resolution of 1 microsecond up to 1 millisecond, a resolution of 1 millisecond (or better) up
//! to one second, and a resolution of 1 second (or better) up to 1,000 seconds. At it's maximum
//! tracked value (1 hour), it would still maintain a resolution of 3.6 seconds (or better).
//!
//! HDR Histogram is designed for recording histograms of value measurements in latency and
//! performance sensitive applications. Measurements show value recording times as low as 3-6
//! nanoseconds on modern (circa 2014) Intel CPUs. The HDR Histogram maintains a fixed cost in both
//! space and time. A Histogram's memory footprint is constant, with no allocation operations
//! involved in recording data values or in iterating through them. The memory footprint is fixed
//! regardless of the number of data value samples recorded, and depends solely on the dynamic
//! range and precision chosen. The amount of work involved in recording a sample is constant, and
//! directly computes storage index locations such that no iteration or searching is ever involved
//! in recording data values.
//!
//! If you are looking for FFI bindings to
//! [`HdrHistogram_c`](https://github.com/HdrHistogram/HdrHistogram_c), you want the
//! [`hdrhistogram_c`](https://crates.io/crates/hdrhistogram_c) crate instead.
//!
//! # Interacting with the library
//!
//! HdrSample's API follows that of the original HdrHistogram Java implementation, with some
//! modifications to make its use more idiomatic in Rust. The description in this section has been
//! adapted from that given by the [Python port](https://github.com/HdrHistogram/HdrHistogram_py),
//! as it gives a nicer first-time introduction to the use of HdrHistogram than the Java docs do.
//!
//! HdrSample is generally used in one of two modes: recording samples, or querying for analytics.
//! In distributed deployments, the recording may be performed remotely (and possibly in multiple
//! locations), to then be aggregated later in a central location for analysis.
//!
//! ## Recording samples
//!
//! A histogram instance is created using the `::new` methods on the `Histogram` struct. These come
//! in three variants: `new`, `new_with_max`, and `new_with_bounds`. The first of these only sets
//! the required precision of the sampled data, but leaves the value range open such that any value
//! may be recorded. A `Histogram` created this way (or one where auto-resize has been explicitly
//! enabled) will automatically resize itself if a value that is too large to fit in the current
//! dataset is encountered. `new_with_max` sets an upper bound on the values to be recorded, and
//! disables auto-resizing, thus preventing any re-allocation during recording. If the application
//! attempts to record a larger value than this maximum bound, the `record` call will return an
//! error. Finally, `new_with_bounds` restricts the lowest representable value of the dataset,
//! such that a smaller range needs to be covered (thus reducing the overall allocation size).
//!
//! For example the example below shows how to create a `Histogram` that can count values in the
//! `[1..3600000]` range with 1% precision, which could be used to track latencies in the range `[1
//! msec..1 hour]`).
//!
//! ```
//! use hdrhistogram::Histogram;
//! let mut hist = Histogram::<u64>::new_with_bounds(1, 60 * 60 * 1000, 2).unwrap();
//!
//! // samples can be recorded using .record, which will error if the value is too small or large
//! hist.record(54321).expect("value 54321 should be in range");
//!
//! // for ergonomics, samples can also be recorded with +=
//! // this call will panic if the value is out of range!
//! hist += 54321;
//!
//! // if the code that generates the values is subject to Coordinated Omission,
//! // the self-correcting record method should be used instead.
//! // for example, if the expected sampling interval is 10 msec:
//! hist.record_correct(54321, 10).expect("value 54321 should be in range");
//! ```
//!
//! Note the `u64` type. This type can be changed to reduce the storage overhead for all the
//! histogram bins, at the cost of a risk of saturating if a large number of samples end up in the
//! same bin.
//!
//! ## Querying samples
//!
//! At any time, the histogram can be queried to return interesting statistical measurements, such
//! as the total number of recorded samples, or the value at a given quantile:
//!
//! ```
//! use hdrhistogram::Histogram;
//! let hist = Histogram::<u64>::new(2).unwrap();
//! // ...
//! println!("# of samples: {}", hist.len());
//! println!("99.9'th percentile: {}", hist.value_at_quantile(0.999));
//! ```
//!
//! Several useful iterators are also provided for quickly getting an overview of the dataset. The
//! simplest one is `iter_recorded()`, which yields one item for every non-empty sample bin. All
//! the HdrHistogram iterators are supported in HdrSample, so look for the `*Iterator` classes in
//! the [Java documentation](https://hdrhistogram.github.io/HdrHistogram/JavaDoc/).
//!
//! ```
//! use hdrhistogram::Histogram;
//! let hist = Histogram::<u64>::new(2).unwrap();
//! // ...
//! for v in hist.iter_recorded() {
//! println!("{}'th percentile of data is {} with {} samples",
//! v.percentile(), v.value_iterated_to(), v.count_at_value());
//! }
//! ```
//!
//! ## Panics and error handling
//!
//! As long as you're using safe, non-panicking functions (see below), this library should never
//! panic. Any panics you encounter are a bug; please file them in the issue tracker.
//!
//! A few functions have their functionality exposed via `AddAssign` and `SubAssign`
//! implementations. These alternate forms are equivalent to simply calling `unwrap()` on the
//! normal functions, so the normal rules of `unwrap()` apply: view with suspicion when used in
//! production code, etc.
//!
//! | Returns Result | Panics on error | Functionality |
//! | ------------------------------ | ------------------ | ------------------------------- |
//! | `h.record(v)` | `h += v` | Increment count for value `v` |
//! | `h.add(h2)` | `h += h2` | Add `h2`'s counts to `h` |
//! | `h.subtract(h2)` | `h -= h2` | Subtract `h2`'s counts from `h` |
//!
//! Other than the panicking forms of the above functions, everything will return `Result` or
//! `Option` if it can fail.
//!
//! ## `usize` limitations
//!
//! Depending on the configured number of significant digits and maximum value, a histogram's
//! internal storage may have hundreds of thousands of cells. Systems with a 16-bit `usize` cannot
//! represent pointer offsets that large, so relevant operations (creation, deserialization, etc)
//! will fail with a suitable error (e.g. `CreationError::UsizeTypeTooSmall`). If you are using such
//! a system and hitting these errors, reducing the number of significant digits will greatly reduce
//! memory consumption (and therefore the need for large `usize` values). Lowering the max value may
//! also help as long as resizing is disabled.
//!
//! 32- and above systems will not have any such issues, as all possible histograms fit within a
//! 32-bit index.
//!
//! ## Floating point accuracy
//!
//! Some calculations inherently involve floating point values, like `value_at_quantile`, and are
//! therefore subject to the precision limits of IEEE754 floating point calculations. The user-
//! visible consequence of this is that in certain corner cases, you might end up with a bucket (and
//! therefore value) that is higher or lower than it would be if the calculation had been done
//! with arbitrary-precision arithmetic. However, double-precision IEEE754 (i.e. `f64`) is very
//! good at its job, so these cases should be rare. Also, we haven't seen a case that was off by
//! more than one bucket.
//!
//! To minimize FP precision losses, we favor working with quantiles rather than percentiles. A
//! quantile represents a portion of a set with a number in `[0, 1]`. A percentile is the same
//! concept, except it uses the range `[0, 100]`. Working just with quantiles means we can skip an
//! FP operation in a few places, and therefore avoid opportunities for precision loss to creep in.
//!
//! # Limitations and Caveats
//!
//! As with all the other HdrHistogram ports, the latest features and bug fixes from the upstream
//! HdrHistogram implementations may not be available in this port. A number of features have also
//! not (yet) been implemented:
//!
//! - Concurrency support (`AtomicHistogram`, `ConcurrentHistogram`, …).
//! - `DoubleHistogram`.
//! - The `Recorder` feature of HdrHistogram.
//! - Value shifting ("normalization").
//! - Textual output methods. These seem almost orthogonal to HdrSample, though it might be
//! convenient if we implemented some relevant traits (CSV, JSON, and possibly simple
//! `fmt::Display`).
//!
//! Most of these should be fairly straightforward to add, as the code aligns pretty well with the
//! original Java/C# code. If you do decide to implement one and send a PR, please make sure you
//! also port the [test
//! cases](https://github.com/HdrHistogram/HdrHistogram/tree/master/src/test/java/org/HdrHistogram),
//! and try to make sure you implement appropriate traits to make the use of the feature as
//! ergonomic as possible.
#![deny(
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_results,
variant_size_differences
)]
// Enable feature(test) is enabled so that we can have benchmarks of private code
#![cfg_attr(all(test, feature = "bench_private"), feature(test))]
#[cfg(all(test, feature = "bench_private"))]
extern crate test;
#[cfg(feature = "serialization")]
#[macro_use]
extern crate nom;
use num_traits::ToPrimitive;
use std::borrow::Borrow;
use std::cmp;
use std::ops::{Add, AddAssign, Sub, SubAssign};
use iterators::HistogramIterator;
/// Min value of a new histogram.
/// Equivalent to `u64::max_value()`, but const functions aren't allowed (yet).
/// See <https://github.com/rust-lang/rust/issues/24111>
const ORIGINAL_MIN: u64 = (-1_i64 >> 63) as u64;
/// Max value of a new histogram.
const ORIGINAL_MAX: u64 = 0;
/// `Histogram` is the core data structure in HdrSample. It records values, and performs analytics.
///
/// At its heart, it keeps the count for recorded samples in "buckets" of values. The resolution
/// and distribution of these buckets is tuned based on the desired highest trackable value, as
/// well as the user-specified number of significant decimal digits to preserve. The values for the
/// buckets are kept in a way that resembles floats and doubles: there is a mantissa and an
/// exponent, and each bucket represents a different exponent. The "sub-buckets" within a bucket
/// represent different values for the mantissa.
///
/// To a first approximation, the sub-buckets of the first
/// bucket would hold the values `0`, `1`, `2`, `3`, …, the sub-buckets of the second bucket would
/// hold `0`, `2`, `4`, `6`, …, the third would hold `0`, `4`, `8`, and so on. However, the low
/// half of each bucket (except bucket 0) is unnecessary, since those values are already covered by
/// the sub-buckets of all the preceeding buckets. Thus, `Histogram` keeps the top half of every
/// such bucket.
///
/// For the purposes of explanation, consider a `Histogram` with 2048 sub-buckets for every bucket,
/// and a lowest discernible value of 1:
///
/// <pre>
/// The 0th bucket covers 0...2047 in multiples of 1, using all 2048 sub-buckets
/// The 1st bucket covers 2048..4097 in multiples of 2, using only the top 1024 sub-buckets
/// The 2nd bucket covers 4096..8191 in multiple of 4, using only the top 1024 sub-buckets
/// ...
/// </pre>
///
/// Bucket 0 is "special" here. It is the only one that has 2048 entries. All the rest have
/// 1024 entries (because their bottom half overlaps with and is already covered by the all of
/// the previous buckets put together). In other words, the `k`'th bucket could represent `0 *
/// 2^k` to `2048 * 2^k` in 2048 buckets with `2^k` precision, but the midpoint of `1024 * 2^k
/// = 2048 * 2^(k-1)`, which is the k-1'th bucket's end. So, we would use the previous bucket
/// for those lower values as it has better precision.
///
#[derive(Debug)]
pub struct Histogram<T: Counter> {
auto_resize: bool,
// >= 2 * lowest_discernible_value
highest_trackable_value: u64,
// >= 1
lowest_discernible_value: u64,
// in [0, 5]
significant_value_digits: u8,
// in [1, 64]
bucket_count: u8,
// 2^(sub_bucket_half_count_magnitude + 1) = [2, 2^18]
sub_bucket_count: u32,
// sub_bucket_count / 2 = [1, 2^17]
sub_bucket_half_count: u32,
// In [0, 17]
sub_bucket_half_count_magnitude: u8,
// The bottom sub bucket's bits set, shifted by unit magnitude.
// The highest bit will be (one-indexed) sub bucket count magnitude + unit_magnitude.
sub_bucket_mask: u64,
// Number of leading zeros that would be used by the largest value in bucket 0.
// in [1, 63]
leading_zero_count_base: u8,
// Largest exponent of 2 that's smaller than the lowest discernible value. In [0, 62].
unit_magnitude: u8,
// low unit_magnitude bits set
unit_magnitude_mask: u64,
max_value: u64,
min_non_zero_value: u64,
total_count: u64,
counts: Vec<T>,
}
/// Module containing the implementations of all `Histogram` iterators.
pub mod iterators;
impl<T: Counter> Histogram<T> {
// ********************************************************************************************
// Histogram administrative read-outs
// ********************************************************************************************
/// Get the current number of distinct values that can be represented in the histogram.
pub fn distinct_values(&self) -> usize {
self.counts.len()
}
/// Get the lowest discernible value for the histogram in its current configuration.
pub fn low(&self) -> u64 {
self.lowest_discernible_value
}
/// Get the highest trackable value for the histogram in its current configuration.
pub fn high(&self) -> u64 {
self.highest_trackable_value
}
/// Get the number of significant value digits kept by this histogram.
pub fn sigfig(&self) -> u8 {
self.significant_value_digits
}
/// Get the total number of samples recorded.
#[deprecated(since = "6.0.0", note = "use `len` instead")]
pub fn count(&self) -> u64 {
self.total_count
}
/// Get the total number of samples recorded.
pub fn len(&self) -> u64 {
self.total_count
}
/// Returns true if this histogram has no recorded values.
pub fn is_empty(&self) -> bool {
self.total_count == 0
}
/// Get the number of buckets used by the histogram to cover the highest trackable value.
///
/// This method differs from `.len()` in that it does not count the sub buckets within each
/// bucket.
///
/// This method is probably only useful for testing purposes.
pub fn buckets(&self) -> u8 {
self.bucket_count
}
// ********************************************************************************************
// Methods for looking up the count for a given value/index
// ********************************************************************************************
/// Find the bucket the given value should be placed in.
/// Returns `None` if the corresponding index cannot be represented in `usize`.
fn index_for(&self, value: u64) -> Option<usize> {
let bucket_index = self.bucket_for(value);
let sub_bucket_index = self.sub_bucket_for(value, bucket_index);
debug_assert!(sub_bucket_index < self.sub_bucket_count);
debug_assert!(bucket_index == 0 || (sub_bucket_index >= self.sub_bucket_half_count));
// Calculate the index for the first entry that will be used in the bucket (halfway through
// sub_bucket_count). For bucket_index 0, all sub_bucket_count entries may be used, but
// bucket_base_index is still set in the middle.
let bucket_base_index =
(i32::from(bucket_index) + 1) << self.sub_bucket_half_count_magnitude;
// Calculate the offset in the bucket. This subtraction will result in a positive value in
// all buckets except the 0th bucket (since a value in that bucket may be less than half
// the bucket's 0 to sub_bucket_count range). However, this works out since we give bucket 0
// twice as much space.
let offset_in_bucket = sub_bucket_index as i32 - self.sub_bucket_half_count as i32;
let index = bucket_base_index + offset_in_bucket;
// This is always non-negative because offset_in_bucket is only negative (and only then by
// sub_bucket_half_count at most) for bucket 0, and bucket_base_index will be halfway into
// bucket 0's sub buckets in that case.
debug_assert!(index >= 0);
index.to_usize()
}
/// Find the bucket the given value should be placed in.
/// If the value is bigger than what this histogram can express, the last valid bucket index
/// is returned instead.
fn index_for_or_last(&self, value: u64) -> usize {
self.index_for(value)
.map_or(self.last_index(), |i| cmp::min(i, self.last_index()))
}
/// Get a mutable reference to the count bucket for the given value, if it is in range.
fn mut_at(&mut self, value: u64) -> Option<&mut T> {
self.index_for(value)
.and_then(move |i| self.counts.get_mut(i))
}
/// Get the index of the last histogram bin.
fn last_index(&self) -> usize {
self.distinct_values()
.checked_sub(1)
.expect("Empty counts array?")
}
// ********************************************************************************************
// Histograms should be cloneable.
// ********************************************************************************************
/// Get a copy of this histogram, corrected for coordinated omission.
///
/// To compensate for the loss of sampled values when a recorded value is larger than the
/// expected interval between value samples, the new histogram will include an auto-generated
/// additional series of decreasingly-smaller (down to the `interval`) value records for each
/// count found in the current histogram that is larger than the `interval`.
///
/// Note: This is a post-correction method, as opposed to the at-recording correction method
/// provided by `record_correct`. The two methods are mutually exclusive, and only one of the
/// two should be be used on a given data set to correct for the same coordinated omission
/// issue.
///
/// See notes in the description of the Histogram calls for an illustration of why this
/// corrective behavior is important.
///
/// If `interval` is larger than 0, add auto-generated value records as appropriate if value is
/// larger than `interval`.
pub fn clone_correct(&self, interval: u64) -> Histogram<T> {
let mut h = Histogram::new_from(self);
for v in self.iter_recorded() {
h.record_n_correct(v.value_iterated_to(), v.count_at_value(), interval)
.expect("Same dimensions; all values should be representable");
}
h
}
/// Overwrite this histogram with the given histogram. All data and statistics in this
/// histogram will be overwritten.
pub fn set_to<B: Borrow<Histogram<T>>>(&mut self, source: B) -> Result<(), AdditionError> {
self.reset();
self.add(source.borrow())
}
/// Overwrite this histogram with the given histogram while correcting for coordinated
/// omission. All data and statistics in this histogram will be overwritten. See
/// `clone_correct` for more detailed explanation about how correction is applied
pub fn set_to_corrected<B: Borrow<Histogram<T>>>(
&mut self,
source: B,
interval: u64,
) -> Result<(), RecordError> {
self.reset();
self.add_correct(source, interval)
}
// ********************************************************************************************
// Add and subtract methods for, well, adding or subtracting two histograms
// ********************************************************************************************
/// Add the contents of another histogram to this one.
///
/// Returns an error if values in the other histogram cannot be stored; see `AdditionError`.
pub fn add<B: Borrow<Histogram<T>>>(&mut self, source: B) -> Result<(), AdditionError> {
let source = source.borrow();
// make sure we can take the values in source
let top = self.highest_equivalent(self.value_for(self.last_index()));
if top < source.max() {
if !self.auto_resize {
return Err(AdditionError::OtherAddendValueExceedsRange);
}
// We're growing the histogram, so new high > old high and is therefore >= 2x low.
self.resize(source.max())
.map_err(|_| AdditionError::ResizeFailedUsizeTypeTooSmall)?;
}
if self.bucket_count == source.bucket_count
&& self.sub_bucket_count == source.sub_bucket_count
&& self.unit_magnitude == source.unit_magnitude
{
// Counts arrays are of the same length and meaning,
// so we can just iterate and add directly:
let mut observed_other_total_count: u64 = 0;
for i in 0..source.distinct_values() {
let other_count = source
.count_at_index(i)
.expect("iterating inside source length");
if other_count != T::zero() {
// indexing is safe: same configuration as `source`, and the index was valid for
// `source`.
self.counts[i] = self.counts[i].saturating_add(other_count);
observed_other_total_count =
observed_other_total_count.saturating_add(other_count.as_u64());
}
}
self.total_count = self.total_count.saturating_add(observed_other_total_count);
let mx = source.max();
if mx > self.max() {
self.update_max(mx);
}
let mn = source.min_nz();
if mn < self.min_nz() {
self.update_min(mn);
}
} else {
// Arrays are not a direct match (or the other could change on the fly in some valid
// way), so we can't just stream through and add them. Instead, go through the array
// and add each non-zero value found at it's proper value:
// Do max value first, to avoid max value updates on each iteration:
let other_max_index = source
.index_for(source.max())
.expect("Index for max value must exist");
let other_count = source
.count_at_index(other_max_index)
.expect("max's index must exist");
self.record_n(source.value_for(other_max_index), other_count)
.expect("Record must succeed; already resized for max value");
// Record the remaining values, up to but not including the max value:
for i in 0..other_max_index {
let other_count = source
.count_at_index(i)
.expect("index before max must exist");
if other_count != T::zero() {
self.record_n(source.value_for(i), other_count)
.expect("Record must succeed; already recorded max value");
}
}
}
// TODO:
// if source.start_time < self.start_time {
// self.start_time = source.start_time;
// }
// if source.end_time > self.end_time {
// self.end_time = source.end_time;
// }
Ok(())
}
/// Add the contents of another histogram to this one, while correcting for coordinated
/// omission.
///
/// To compensate for the loss of sampled values when a recorded value is larger than the
/// expected interval between value samples, the values added will include an auto-generated
/// additional series of decreasingly-smaller (down to the given `interval`) value records for
/// each count found in the current histogram that is larger than `interval`.
///
/// Note: This is a post-recording correction method, as opposed to the at-recording correction
/// method provided by `record_correct`. The two methods are mutually exclusive, and only one
/// of the two should be be used on a given data set to correct for the same coordinated
/// omission issue.
///
/// See notes in the description of the `Histogram` calls for an illustration of why this
/// corrective behavior is important.
///
/// See `RecordError` for error conditions.
pub fn add_correct<B: Borrow<Histogram<T>>>(
&mut self,
source: B,
interval: u64,
) -> Result<(), RecordError> {
let source = source.borrow();
for v in source.iter_recorded() {
self.record_n_correct(v.value_iterated_to(), v.count_at_value(), interval)?;
}
Ok(())
}
/// Subtract the contents of another histogram from this one.
///
/// See `SubtractionError` for error conditions.
pub fn subtract<B: Borrow<Histogram<T>>>(
&mut self,
subtrahend: B,
) -> Result<(), SubtractionError> {
let subtrahend = subtrahend.borrow();
// make sure we can take the values in source
let top = self.highest_equivalent(self.value_for(self.last_index()));
if top < self.highest_equivalent(subtrahend.max()) {
return Err(SubtractionError::SubtrahendValueExceedsMinuendRange);
}
let old_min_highest_equiv = self.highest_equivalent(self.min());
let old_max_lowest_equiv = self.lowest_equivalent(self.max());
// If total_count is at the max value, it may have saturated, so we must restat
let mut needs_restat = self.total_count == u64::max_value();
for i in 0..subtrahend.distinct_values() {
let other_count = subtrahend
.count_at_index(i)
.expect("index inside subtrahend len must exist");
if other_count != T::zero() {
let other_value = subtrahend.value_for(i);
{
let mut_count = self.mut_at(other_value);
if let Some(c) = mut_count {
// TODO Perhaps we should saturating sub here? Or expose some form of
// pluggability so users could choose to error or saturate? Both seem
// useful. It's also sort of inconsistent with overflow, which now
// saturates.
*c = (*c)
.checked_sub(&other_count)
.ok_or(SubtractionError::SubtrahendCountExceedsMinuendCount)?;
} else {
panic!("Tried to subtract value outside of range: {}", other_value);
}
}
// we might have just set the min / max to have zero count.
if other_value <= old_min_highest_equiv || other_value >= old_max_lowest_equiv {
needs_restat = true;
}
if !needs_restat {
// if we're not already going to recalculate everything, subtract from
// total_count
self.total_count = self
.total_count
.checked_sub(other_count.as_u64())
.expect("total count underflow on subtraction");
}
}
}
if needs_restat {
let l = self.distinct_values();
self.restat(l);
}
Ok(())
}
// ********************************************************************************************
// Setters and resetters.
// ********************************************************************************************
/// Clear the contents of this histogram while preserving its statistics and configuration.
pub fn clear(&mut self) {
for c in &mut self.counts {
*c = T::zero();
}
self.total_count = 0;
}
/// Reset the contents and statistics of this histogram, preserving only its configuration.
pub fn reset(&mut self) {
self.clear();
self.reset_max(ORIGINAL_MAX);
self.reset_min(ORIGINAL_MIN);
// self.normalizing_index_offset = 0;
// self.start_time = time::Instant::now();
// self.end_time = time::Instant::now();
// self.tag = String::new();
}
/// Control whether or not the histogram can auto-resize and auto-adjust it's highest trackable
/// value as high-valued samples are recorded.
pub fn auto(&mut self, enabled: bool) {
self.auto_resize = enabled;
}
// ********************************************************************************************
// Construction.
// ********************************************************************************************
/// Construct an auto-resizing `Histogram` with a lowest discernible value of 1 and an
/// auto-adjusting highest trackable value. Can auto-resize up to track values up to
/// `(i64::max_value() / 2)`.
///
/// See [`new_with_bounds`] for info on `sigfig`.
///
/// [`new_with_bounds`]: #method.new_with_bounds
pub fn new(sigfig: u8) -> Result<Histogram<T>, CreationError> {
let mut h = Self::new_with_bounds(1, 2, sigfig);
if let Ok(ref mut h) = h {
h.auto_resize = true;
}
h
}
/// Construct a `Histogram` given a known maximum value to be tracked, and a number of
/// significant decimal digits. The histogram will be constructed to implicitly track
/// (distinguish from 0) values as low as 1. Auto-resizing will be disabled.
///
/// See [`new_with_bounds`] for info on `high` and `sigfig`.
///
/// [`new_with_bounds`]: #method.new_with_bounds
pub fn new_with_max(high: u64, sigfig: u8) -> Result<Histogram<T>, CreationError> {
Self::new_with_bounds(1, high, sigfig)
}
/// Construct a `Histogram` with known upper and lower bounds for recorded sample values.
///
/// `low` is the lowest value that can be discerned (distinguished from 0) by the histogram,
/// and must be a positive integer that is >= 1. It may be internally rounded down to nearest
/// power of 2. Providing a lowest discernible value (`low`) is useful is situations where the
/// units used for the histogram's values are much smaller that the minimal accuracy required.
/// E.g. when tracking time values stated in nanosecond units, where the minimal accuracy
/// required is a microsecond, the proper value for `low` would be 1000. If you're not sure,
/// use 1.
///
/// `high` is the highest value to be tracked by the histogram, and must be a
/// positive integer that is `>= (2 * low)`. If you're not sure, use `u64::max_value()`.
///
/// `sigfig` Specifies the number of significant figures to maintain. This is the number of
/// significant decimal digits to which the histogram will maintain value resolution and
/// separation. Must be in the range [0, 5]. If you're not sure, use 3. As `sigfig` increases,
/// memory usage grows exponentially, so choose carefully if there will be many histograms in
/// memory at once or if storage is otherwise a concern.
///
/// Returns an error if the provided parameters are invalid; see `CreationError`.
pub fn new_with_bounds(low: u64, high: u64, sigfig: u8) -> Result<Histogram<T>, CreationError> {
// Verify argument validity
if low < 1 {
return Err(CreationError::LowIsZero);
}
if low > u64::max_value() / 2 {
// avoid overflow in 2 * low
return Err(CreationError::LowExceedsMax);
}
if high < 2 * low {
return Err(CreationError::HighLessThanTwiceLow);
}
if sigfig > 5 {
return Err(CreationError::SigFigExceedsMax);
}
// Given a 3 decimal point accuracy, the expectation is obviously for "+/- 1 unit at 1000".
// It also means that it's "ok to be +/- 2 units at 2000". The "tricky" thing is that it is
// NOT ok to be +/- 2 units at 1999. Only starting at 2000. So internally, we need to
// maintain single unit resolution to 2x 10^decimal_points.
// largest value with single unit resolution, in [2, 200_000].
let largest = 2 * 10_u32.pow(u32::from(sigfig));
let unit_magnitude = (low as f64).log2().floor() as u8;
let unit_magnitude_mask = (1 << unit_magnitude) - 1;
// We need to maintain power-of-two sub_bucket_count (for clean direct indexing) that is
// large enough to provide unit resolution to at least
// largest_value_with_single_unit_resolution. So figure out
// largest_value_with_single_unit_resolution's nearest power-of-two (rounded up), and use
// that.
// In [1, 18]. 2^18 > 2 * 10^5 (the largest possible
// largest_value_with_single_unit_resolution)
let sub_bucket_count_magnitude = (f64::from(largest)).log2().ceil() as u8;
let sub_bucket_half_count_magnitude = sub_bucket_count_magnitude - 1;
let sub_bucket_count = 1_u32 << u32::from(sub_bucket_count_magnitude);
if unit_magnitude + sub_bucket_count_magnitude > 63 {
// sub_bucket_count entries can't be represented, with unit_magnitude applied, in a
// u64. Technically it still sort of works if their sum is 64: you can represent all
// but the last number in the shifted sub_bucket_count. However, the utility of such a
// histogram vs ones whose magnitude here fits in 63 bits is debatable, and it makes
// it harder to work through the logic. Sums larger than 64 are totally broken as
// leading_zero_count_base would go negative.
return Err(CreationError::CannotRepresentSigFigBeyondLow);
};
let sub_bucket_half_count = sub_bucket_count / 2;
// sub_bucket_count is always at least 2, so subtraction won't underflow
let sub_bucket_mask = (u64::from(sub_bucket_count) - 1) << unit_magnitude;
let mut h = Histogram {
auto_resize: false,
highest_trackable_value: high,
lowest_discernible_value: low,
significant_value_digits: sigfig,
// set by resize() below
bucket_count: 0,
sub_bucket_count,
// Establish leading_zero_count_base, used in bucket_index_of() fast path:
// subtract the bits that would be used by the largest value in bucket 0.
leading_zero_count_base: 64 - unit_magnitude - sub_bucket_count_magnitude,
sub_bucket_half_count_magnitude,
unit_magnitude,
sub_bucket_half_count,
sub_bucket_mask,
unit_magnitude_mask,
max_value: ORIGINAL_MAX,
min_non_zero_value: ORIGINAL_MIN,
total_count: 0,
// set by alloc() below
counts: Vec::new(),
};
// Already checked that high >= 2*low
h.resize(high)
.map_err(|_| CreationError::UsizeTypeTooSmall)?;
Ok(h)
}
/// Construct a `Histogram` with the same range settings as a given source histogram,
/// duplicating the source's start/end timestamps (but NOT its contents).
pub fn new_from<F: Counter>(source: &Histogram<F>) -> Histogram<T> {
let mut h = Self::new_with_bounds(
source.lowest_discernible_value,
source.highest_trackable_value,
source.significant_value_digits,
)
.expect("Using another histogram's parameters failed");
// h.start_time = source.start_time;
// h.end_time = source.end_time;
h.auto_resize = source.auto_resize;
h.counts.resize(source.distinct_values(), T::zero());
h
}
// ********************************************************************************************
// Recording samples.
// ********************************************************************************************
/// Record `value` in the histogram.
///
/// Returns an error if `value` exceeds the highest trackable value and auto-resize is
/// disabled.
pub fn record(&mut self, value: u64) -> Result<(), RecordError> {
self.record_n(value, T::one())
}
/// Record `value` in the histogram, clamped to the range of the histogram.
///
/// This method cannot fail, as any values that are too small or too large to be tracked will
/// automatically be clamed to be in range. Be aware that this *will* hide extreme outliers
/// from the resulting histogram without warning. Since the values are clamped, the histogram
/// will also not be resized to accomodate the value, even if auto-resize is enabled.
pub fn saturating_record(&mut self, value: u64) {
self.saturating_record_n(value, T::one())
}
/// Record multiple samples for a value in the histogram, adding to the value's current count.
///
/// `count` is the number of occurrences of this value to record.
///
/// Returns an error if `value` cannot be recorded; see `RecordError`.
pub fn record_n(&mut self, value: u64, count: T) -> Result<(), RecordError> {
self.record_n_inner(value, count, false)
}
/// Record multiple samples for a value in the histogram, each one clamped to the histogram's
/// range.
///
/// `count` is the number of occurrences of this value to record.
///
/// This method cannot fail, as values that are too small or too large to be recorded will
/// automatically be clamed to be in range. Be aware that this *will* hide extreme outliers
/// from the resulting histogram without warning. Since the values are clamped, the histogram
/// will also not be resized to accomodate the value, even if auto-resize is enabled.
pub fn saturating_record_n(&mut self, value: u64, count: T) {
self.record_n_inner(value, count, true).unwrap()
}
fn record_n_inner(&mut self, mut value: u64, count: T, clamp: bool) -> Result<(), RecordError> {
let recorded_without_resize = if let Some(c) = self.mut_at(value) {
*c = (*c).saturating_add(count);
true
} else {
false
};
if !recorded_without_resize {
if clamp {
value = if value > self.highest_trackable_value {
self.highest_trackable_value
} else {
// must be smaller than the lowest_discernible_value, since self.mut_at(value)
// failed, and it's not too large (per above).
self.lowest_discernible_value
};
let c = self
.mut_at(value)
.expect("unwrap must succeed since low and high are always representable");
*c = c.saturating_add(count);
} else if !self.auto_resize {
return Err(RecordError::ValueOutOfRangeResizeDisabled);
} else {
// We're growing the histogram, so new high > old high and is therefore >= 2x low.
self.resize(value)
.map_err(|_| RecordError::ResizeFailedUsizeTypeTooSmall)?;
self.highest_trackable_value =
self.highest_equivalent(self.value_for(self.last_index()));
{
let c = self.mut_at(value).expect("value should fit after resize");
// after resize, should be no possibility of overflow because this is a new slot
*c = (*c)
.checked_add(&count)
.expect("count overflow after resize");
}
}
}
self.update_min_max(value);
self.total_count = self.total_count.saturating_add(count.as_u64());
Ok(())
}
/// Record a value in the histogram while correcting for coordinated omission.
///
/// See `record_n_correct` for further documentation.
pub fn record_correct(&mut self, value: u64, interval: u64) -> Result<(), RecordError> {
self.record_n_correct(value, T::one(), interval)
}
/// Record multiple values in the histogram while correcting for coordinated omission.
///
/// To compensate for the loss of sampled values when a recorded value is larger than the
/// expected interval between value samples, this method will auto-generate and record an
/// additional series of decreasingly-smaller (down to `interval`) value records.
///
/// Note: This is a at-recording correction method, as opposed to the post-recording correction
/// method provided by `correct_clone`. The two methods are mutually exclusive, and only one of
/// the two should be be used on a given data set to correct for the same coordinated omission
/// issue.
///
/// Returns an error if `value` exceeds the highest trackable value and auto-resize is
/// disabled.
pub fn record_n_correct(
&mut self,
value: u64,
count: T,
interval: u64,
) -> Result<(), RecordError> {
self.record_n(value, count)?;
if interval == 0 {
return Ok(());
}
if value > interval {
// only enter loop when calculations will stay non-negative
let mut missing_value = value - interval;
while missing_value >= interval {
self.record_n_inner(missing_value, count, false)?;
missing_value -= interval;
}
}
Ok(())
}
// ********************************************************************************************
// Iterators
// ********************************************************************************************
/// Iterate through histogram values by quantile levels.
///
/// The iteration mechanic for this iterator may appear somewhat confusing, but it yields
/// fairly pleasing output. The iterator starts with a *quantile step size* of
/// `1/halving_period`. For every iteration, it yields a value whose quantile is that much
/// greater than the previously emitted quantile (i.e., initially 0, 0.1, 0.2, etc.). Once
/// `halving_period` values have been emitted, the quantile step size is halved, and the
/// iteration continues.
///
/// `ticks_per_half_distance` must be at least 1.
///
/// The iterator yields an `iterators::IterationValue` struct.
///
/// One subtlety of this iterator is that you can reach a value whose cumulative count yields
/// a quantile of 1.0 far sooner than the quantile iteration would reach 1.0. Consider a
/// histogram with count 1 at value 1, and count 1000000 at value 1000. At any quantile
/// iteration above `1/1000001 = 0.000000999`, iteration will have necessarily proceeded to
/// the index for value 1000, which has all the remaining counts, and therefore quantile (for
/// the value) of 1.0. This is why `IterationValue` has both `quantile()` and
/// `quantile_iterated_to()`. Additionally, to avoid a bunch of unhelpful iterations once
/// iteration has reached the last value with non-zero count, quantile iteration will skip
/// straight to 1.0 as well.
///
/// ```
/// use hdrhistogram::Histogram;
/// use hdrhistogram::iterators::IterationValue;
/// let mut hist = Histogram::<u64>::new_with_max(10000, 4).unwrap();
/// for i in 0..10000 {
/// hist += i;
/// }
///
/// let mut perc = hist.iter_quantiles(1);
///
/// println!("{:?}", hist.iter_quantiles(1).collect::<Vec<_>>());
///
/// assert_eq!(
/// perc.next(),
/// Some(IterationValue::new(hist.value_at_quantile(0.0001), 0.0001, 0.0, 1, 1))
/// );
/// // step size = 50
/// assert_eq!(
/// perc.next(),
/// Some(IterationValue::new(hist.value_at_quantile(0.5), 0.5, 0.5, 1, 5000 - 1))
/// );
/// // step size = 25