├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.bk 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: cargo 3 | rust: 4 | - stable 5 | - beta 6 | - nightly 7 | os: linux 8 | env: TYPE=default RUST_BACKTRACE=1 9 | matrix: 10 | include: 11 | - os: linux 12 | rust: nightly 13 | env: TYPE=rustfmt RUST_BACKTRACE=1 14 | script: 15 | - cargo install -f rustfmt || exit 0 16 | - cargo fmt -- --write-mode=diff --force 17 | - os: linux 18 | rust: nightly 19 | env: TYPE=clippy RUST_BACKTRACE=1 20 | script: 21 | - cargo install -f clippy || exit 0 22 | - cargo clippy 23 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # The Code of Conduct 2 | 3 | This document is based on the [Rust Code of Conduct](https://www.rust-lang.org/conduct.html) and outlines the standard of conduct which is both expected and enforced as part of this project. You may also view this [Code of Conduct](https://brayniac.github.io/conduct/index.html) online. 4 | 5 | ## Conduct 6 | 7 | **Contact**: [conduct@brayniac.org](mailto:conduct@brayniac.org) 8 | 9 | * We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. 10 | * Avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. 11 | * Please be kind and courteous. There's no need to be mean or rude. 12 | * Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. 13 | * Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. 14 | * We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behaviour. We interpret the term "harassment" as including the definition in the Citizen Code of Conduct; if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. 15 | * Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the repository Owners immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. 16 | * Likewise any spamming, trolling, flaming, baiting or other attention-stealing behaviour is not welcome. 17 | 18 | ## Moderation 19 | 20 | These are the policies for upholding our community's standards of conduct. If you feel that a thread needs moderation, please use the contact information above, or mention @brayniac in the thread. 21 | 22 | 1. Remarks that violate this Code of Conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) 23 | 2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. 24 | 25 | In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. 26 | 27 | And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. 28 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "histogram" 3 | version = "0.6.10-pre" 4 | authors = ["Brian Martin "] 5 | 6 | license = "MIT/Apache-2.0" 7 | 8 | description = "histogram storage and percentile metrics with precision guarentees" 9 | 10 | homepage = "https://github.com/brayniac/histogram" 11 | documentation = "https://docs.rs/histogram" 12 | repository = "https://github.com/brayniac/histogram" 13 | 14 | readme = "README.md" 15 | 16 | keywords = [ "histogram", "percentile", "statistics", "stats" ] 17 | 18 | categories = [ "data-structures" ] 19 | 20 | edition = "2018" 21 | 22 | [dependencies] 23 | thiserror = "^1" 24 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Brian Martin and other Histogram contributors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Brian Martin and other Histogram contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # histogram - histogram storage and percentile stats 2 | 3 | Histogram is a stats library for rust which provides histogram storage with 4 | percentile stats. It maintains precision guarentees throughout the range of 5 | stored values. The bucketing algorithm makes use of logarithmic outer buckets 6 | with linear steps between those buckets. This allows for storing a wide range 7 | of values - like latency in nanoseconds from one nanosecond all that way to 8 | minutes while maintaining precision of those recorded values. 9 | 10 | [![conduct-badge][]][conduct] [![travis-badge][]][travis] [![downloads-badge][] ![release-badge][]][crate] [![license-badge][]](#license) 11 | 12 | [conduct-badge]: https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg 13 | [travis-badge]: https://img.shields.io/travis/brayniac/histogram/master.svg 14 | [downloads-badge]: https://img.shields.io/crates/d/histogram.svg 15 | [release-badge]: https://img.shields.io/crates/v/histogram.svg 16 | [license-badge]: https://img.shields.io/crates/l/histogram.svg 17 | [conduct]: https://brayniac.github.io/conduct 18 | [travis]: https://travis-ci.org/brayniac/histogram 19 | [crate]: https://crates.io/crates/histogram 20 | [Cargo]: https://github.com/rust-lang/cargo 21 | 22 | ## Code of Conduct 23 | 24 | **NOTE**: All conversations and contributions to this project shall adhere to the [Code of Conduct][conduct] 25 | 26 | ## Usage 27 | 28 | To use `histogram`, first add this to your `Cargo.toml`: 29 | 30 | ```toml 31 | [dependencies] 32 | histogram = "*" 33 | ``` 34 | 35 | Then, add this to your crate root: 36 | 37 | ```rust 38 | extern crate histogram; 39 | ``` 40 | 41 | The API documentation of this library can be found at 42 | [docs.rs/histogram](https://docs.rs/histogram/). 43 | 44 | ## Features 45 | 46 | * Values are stored with precision guarentees 47 | * Pre-allocated on initialization 48 | * Retrieve percentile stats 49 | 50 | ## License 51 | 52 | Licensed under either of 53 | 54 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 55 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 56 | 57 | at your option. 58 | 59 | ## Contribution 60 | 61 | Unless you explicitly state otherwise, any contribution intentionally 62 | submitted for inclusion in the work by you, as defined in the Apache-2.0 63 | license, shall be dual licensed as above, without any additional terms or 64 | conditions. 65 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A native rust implementation of a histogram and percentiles which can offer 2 | //! specified precision across the full range of stored values. This library is 3 | //! inspired by the `HdrHistogram` project. 4 | //! 5 | //! # Goals 6 | //! * maintain precision across full value range 7 | //! * provide percentile metrics for stored data 8 | //! * pre-allocated datastructure 9 | //! 10 | //! # Future work 11 | //! * unknown 12 | //! 13 | //! # Usage 14 | //! 15 | //! Create a new histogram, call increment for every value, retrieve percentile 16 | //! stats. 17 | //! 18 | //! Note that the incremented and decremented values have the 19 | //! precision which is given upon creation of the histogram (by 20 | //! default 3 decimals). This means that increment of x and decrement 21 | //! of y might lead net effect of zero, if x and y are of similar 22 | //! size. 23 | //! 24 | //! # Example 25 | //! 26 | //! Create a histogram, increment values, show percentiles 27 | //! 28 | //! ``` 29 | //! use histogram::Histogram; 30 | //! 31 | //! // create a histogram with default config 32 | //! let mut histogram = Histogram::new(); 33 | //! 34 | //! let mut value = 0; 35 | //! 36 | //! for i in 1..100 { 37 | //! histogram.increment(i); 38 | //! } 39 | //! 40 | //! // print percentiles from the histogram 41 | //! println!("Percentiles: p50: {} ns p90: {} ns p99: {} ns p999: {}", 42 | //! histogram.percentile(50.0).unwrap(), 43 | //! histogram.percentile(90.0).unwrap(), 44 | //! histogram.percentile(99.0).unwrap(), 45 | //! histogram.percentile(99.9).unwrap(), 46 | //! ); 47 | //! 48 | //! // print additional statistics 49 | //! println!("Latency (ns): Min: {} Avg: {} Max: {} StdDev: {}", 50 | //! histogram.minimum().unwrap(), 51 | //! histogram.mean().unwrap(), 52 | //! histogram.maximum().unwrap(), 53 | //! histogram.stddev().unwrap(), 54 | //! ); 55 | //! ``` 56 | 57 | #![cfg_attr(feature = "cargo-clippy", deny(warnings))] 58 | 59 | use std::fmt; 60 | use std::mem; 61 | 62 | use thiserror::Error; 63 | 64 | /// Represents errors that can occur in histogram data lookup or storage. 65 | #[derive(Debug, Error, PartialEq)] 66 | pub enum HistogramError { 67 | #[error("invalid percentile value")] 68 | InvalidPercentileValue, 69 | #[error("no data")] 70 | NoData, 71 | #[error("overflow")] 72 | Overflow, 73 | #[error("sample value too large")] 74 | SampleValueTooLarge, 75 | #[error("sample value unknown")] 76 | SampleValueUnknown, 77 | #[error("large sample value underflow")] 78 | SampleValueUnderflow, 79 | #[error("underflow")] 80 | Underflow, 81 | #[error("unknown failure")] 82 | UnknownFailure, 83 | } 84 | 85 | /// A configuration struct for building custom `Histogram`s. 86 | #[derive(Clone, Copy)] 87 | pub struct Config { 88 | precision: u32, 89 | max_memory: u32, 90 | max_value: u64, 91 | radix: u32, 92 | } 93 | 94 | impl Default for Config { 95 | fn default() -> Config { 96 | Config { 97 | precision: 3, 98 | max_memory: 0, 99 | max_value: 60_000_000_000, 100 | radix: 10, 101 | } 102 | } 103 | } 104 | 105 | impl Config { 106 | /// create a new Histogram Config with defaults 107 | /// 108 | /// # Example 109 | /// ``` 110 | /// # use histogram::Histogram; 111 | /// let mut c = Histogram::configure(); 112 | /// ``` 113 | pub fn new() -> Config { 114 | Default::default() 115 | } 116 | 117 | /// set HistogramConfig precision 118 | /// 119 | /// # Example 120 | /// ``` 121 | /// # use histogram::Histogram; 122 | /// let mut c = Histogram::configure(); 123 | /// c.precision(4); // set to 4 significant figures 124 | /// ``` 125 | pub fn precision(mut self, precision: u32) -> Self { 126 | self.precision = precision; 127 | self 128 | } 129 | 130 | /// set HistogramConfig memory limit 131 | /// 132 | /// # Example 133 | /// ``` 134 | /// # use histogram::Histogram; 135 | /// let mut c = Histogram::configure(); 136 | /// c.max_memory(1024*1024); // cap Histogram at 1MB of data 137 | /// ``` 138 | pub fn max_memory(mut self, bytes: u32) -> Self { 139 | self.max_memory = bytes; 140 | self 141 | } 142 | 143 | /// set HistogramConfig value limit 144 | /// 145 | /// # Example 146 | /// ``` 147 | /// # use histogram::Histogram; 148 | /// let mut c = Histogram::configure(); 149 | /// c.max_value(1000); // values above 1000 will not be stored 150 | /// ``` 151 | pub fn max_value(mut self, max: u64) -> Self { 152 | self.max_value = max; 153 | self 154 | } 155 | 156 | /// Build a new histogram based on the current configuration 157 | /// values. Return `None` if the new histogram would require more 158 | /// than the [configured memory size](#method.max_memory). 159 | pub fn build(self) -> Option { 160 | Histogram::configured(self) 161 | } 162 | } 163 | 164 | #[derive(Clone, Copy)] 165 | struct Counters { 166 | entries_total: u64, 167 | missed_unknown: u64, 168 | missed_large: u64, 169 | } 170 | 171 | impl Default for Counters { 172 | fn default() -> Counters { 173 | Counters { 174 | entries_total: 0, 175 | missed_unknown: 0, 176 | missed_large: 0, 177 | } 178 | } 179 | } 180 | 181 | impl Counters { 182 | fn new() -> Counters { 183 | Default::default() 184 | } 185 | 186 | fn clear(&mut self) -> &mut Self { 187 | self.entries_total = 0; 188 | self.missed_unknown = 0; 189 | self.missed_large = 0; 190 | self 191 | } 192 | } 193 | 194 | #[derive(Clone)] 195 | struct Data { 196 | data: Vec, 197 | counters: Counters, 198 | } 199 | 200 | #[derive(Clone, Copy)] 201 | struct Properties { 202 | buckets_inner: u32, 203 | linear_max: u64, 204 | linear_power: u32, 205 | } 206 | 207 | /// the main datastructure 208 | #[derive(Clone)] 209 | pub struct Histogram { 210 | config: Config, 211 | data: Data, 212 | properties: Properties, 213 | } 214 | 215 | /// value-quantized section of `Histogram` 216 | #[derive(Clone, Copy, Debug)] 217 | pub struct Bucket { 218 | id: u64, 219 | count: u64, 220 | value: u64, 221 | width: u64, 222 | } 223 | 224 | impl Bucket { 225 | /// return the sample value for the bucket 226 | /// 227 | /// # Example 228 | /// ``` 229 | /// # use histogram::Histogram; 230 | /// let mut h = Histogram::new(); 231 | /// let b = h.into_iter().next().unwrap(); 232 | /// assert_eq!(b.value(), 0); 233 | /// ``` 234 | pub fn value(self) -> u64 { 235 | self.value 236 | } 237 | 238 | /// return the sample counts for the bucket 239 | /// 240 | /// # Example 241 | /// ``` 242 | /// # use histogram::Histogram; 243 | /// let h = Histogram::new(); 244 | /// let b = h.into_iter().next().unwrap(); 245 | /// assert_eq!(b.count(), 0); 246 | /// ``` 247 | pub fn count(self) -> u64 { 248 | self.count 249 | } 250 | 251 | /// return the bucket id 252 | /// 253 | /// # Example 254 | /// ``` 255 | /// # use histogram::Histogram; 256 | /// let h = Histogram::new(); 257 | /// let b = h.into_iter().next().unwrap(); 258 | /// assert_eq!(b.id(), 0); 259 | /// ``` 260 | pub fn id(self) -> u64 { 261 | self.id 262 | } 263 | 264 | /// return the width of the bucket 265 | /// 266 | /// # Example 267 | /// ``` 268 | /// # use histogram::Histogram; 269 | /// let h = Histogram::new(); 270 | /// let b = h.into_iter().next().unwrap(); 271 | /// assert_eq!(b.width(), 1); 272 | /// ``` 273 | pub fn width(self) -> u64 { 274 | self.width 275 | } 276 | } 277 | 278 | /// Iterator over a Histogram's buckets. 279 | pub struct Iter<'a> { 280 | hist: &'a Histogram, 281 | index: usize, 282 | } 283 | 284 | impl<'a> Iter<'a> { 285 | fn new(hist: &'a Histogram) -> Iter<'a> { 286 | Iter { hist, index: 0 } 287 | } 288 | } 289 | 290 | impl<'a> Iterator for Iter<'a> { 291 | type Item = Bucket; 292 | 293 | fn next(&mut self) -> Option { 294 | let limit = self.hist.get_index(self.hist.config.max_value).unwrap(); 295 | if self.index > limit { 296 | None 297 | } else { 298 | let current = self.index; 299 | 300 | // clamp the value at max value 301 | let mut value = self.hist.index_value(current); 302 | if value > self.hist.config.max_value { 303 | value = self.hist.config.max_value; 304 | self.index = limit + 1; 305 | } 306 | 307 | // measure width of current bucket 308 | let width = if current == 0 { 309 | 1 310 | } else { 311 | value - self.hist.index_value(current - 1) 312 | }; 313 | self.index += 1; 314 | Some(Bucket { 315 | id: current as u64, 316 | count: self.hist.data.data[current], 317 | value, 318 | width, 319 | }) 320 | } 321 | } 322 | } 323 | 324 | impl<'a> IntoIterator for &'a Histogram { 325 | type Item = Bucket; 326 | type IntoIter = Iter<'a>; 327 | 328 | fn into_iter(self) -> Self::IntoIter { 329 | Iter::new(self) 330 | } 331 | } 332 | 333 | impl fmt::Debug for Histogram { 334 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 335 | write!(f, "({} total)", self.data.counters.entries_total) 336 | } 337 | } 338 | 339 | impl Default for Histogram { 340 | fn default() -> Histogram { 341 | Config::new().build().unwrap() 342 | } 343 | } 344 | 345 | impl Histogram { 346 | /// create a new Histogram 347 | /// 348 | /// # Example 349 | /// ``` 350 | /// # use histogram::Histogram; 351 | /// let mut h = Histogram::new(); 352 | /// ``` 353 | pub fn new() -> Histogram { 354 | Default::default() 355 | } 356 | 357 | /// configure a Histogram 358 | /// 359 | /// # Example 360 | /// ``` 361 | /// # use histogram::Histogram; 362 | /// let mut h = Histogram::configure() 363 | /// .max_value(10_000) 364 | /// .build() 365 | /// .unwrap(); 366 | /// ``` 367 | pub fn configure() -> Config { 368 | Config::default() 369 | } 370 | 371 | fn configured(config: Config) -> Option { 372 | let buckets_inner: u32 = config.radix.pow(config.precision); 373 | let linear_power: u32 = 32 - buckets_inner.leading_zeros(); 374 | let linear_max: u64 = 2.0_f64.powi(linear_power as i32) as u64; 375 | let max_value_power: u32 = 64 - config.max_value.leading_zeros(); 376 | 377 | let buckets_outer = if max_value_power > linear_power { 378 | max_value_power - linear_power 379 | } else { 380 | 0 381 | }; 382 | 383 | let buckets_total = buckets_inner * buckets_outer + linear_max as u32; 384 | let memory_used = buckets_total * mem::size_of::() as u32; 385 | 386 | if config.max_memory > 0 && config.max_memory < memory_used { 387 | return None; 388 | } 389 | 390 | let data = vec![0; buckets_total as usize]; 391 | 392 | let counters = Counters::new(); 393 | 394 | Some(Histogram { 395 | config, 396 | data: Data { data, counters }, 397 | properties: Properties { 398 | buckets_inner, 399 | linear_max, 400 | linear_power, 401 | }, 402 | }) 403 | } 404 | 405 | /// clear the histogram data 406 | /// 407 | /// # Example 408 | /// ``` 409 | /// # use histogram::Histogram; 410 | /// let mut h = Histogram::new(); 411 | /// 412 | /// h.increment(1); 413 | /// assert_eq!(h.entries(), 1); 414 | /// h.clear(); 415 | /// assert_eq!(h.entries(), 0); 416 | /// ``` 417 | pub fn clear(&mut self) { 418 | // clear everything manually, weird results in practice? 419 | self.data.counters.clear(); 420 | for x in &mut self.data.data { 421 | *x = 0; 422 | } 423 | } 424 | 425 | /// increment the count for a value 426 | /// 427 | /// # Example 428 | /// ``` 429 | /// use histogram::Histogram; 430 | /// 431 | /// let mut h = Histogram::new(); 432 | /// 433 | /// h.increment(1); 434 | /// assert_eq!(h.get(1).unwrap(), 1); 435 | /// ``` 436 | pub fn increment(&mut self, value: u64) -> Result<(), HistogramError> { 437 | self.increment_by(value, 1_u64) 438 | } 439 | 440 | /// record additional counts for value 441 | /// 442 | /// # Example 443 | /// ``` 444 | /// # use histogram::Histogram; 445 | /// let mut h = Histogram::new(); 446 | /// 447 | /// h.increment_by(1, 1); 448 | /// assert_eq!(h.get(1).unwrap(), 1); 449 | /// 450 | /// h.increment_by(2, 2); 451 | /// assert_eq!(h.get(2).unwrap(), 2); 452 | /// 453 | /// h.increment_by(10, 10); 454 | /// assert_eq!(h.get(10).unwrap(), 10); 455 | /// ``` 456 | pub fn increment_by(&mut self, value: u64, count: u64) -> Result<(), HistogramError> { 457 | self.data.counters.entries_total = self.data.counters.entries_total.saturating_add(count); 458 | if value > self.config.max_value { 459 | self.data.counters.missed_large = self.data.counters.missed_large.saturating_add(count); 460 | Err(HistogramError::SampleValueTooLarge) 461 | } else { 462 | match self.get_index(value) { 463 | Some(index) => { 464 | self.data.data[index] = self.data.data[index].saturating_add(count); 465 | Ok(()) 466 | } 467 | None => { 468 | self.data.counters.missed_unknown = 469 | self.data.counters.missed_unknown.saturating_add(count); 470 | Err(HistogramError::SampleValueUnknown) 471 | } 472 | } 473 | } 474 | } 475 | 476 | /// decrement the count for a value. This functionality is best 477 | /// used to remove previously inserted from the histogram. 478 | /// 479 | /// # Example 480 | /// ``` 481 | /// # use histogram::Histogram; 482 | /// let mut h = Histogram::new(); 483 | /// 484 | /// h.increment(1).unwrap(); 485 | /// assert_eq!(h.get(1).unwrap(), 1); 486 | /// h.decrement(1).unwrap(); 487 | /// assert_eq!(h.get(1).unwrap(), 0); 488 | /// ``` 489 | pub fn decrement(&mut self, value: u64) -> Result<(), HistogramError> { 490 | self.decrement_by(value, 1_u64) 491 | } 492 | 493 | /// remove count for value from histogram. This functionality is 494 | /// best used to remove previously inserted from the 495 | /// histogram. 496 | /// 497 | /// # Example 498 | /// ``` 499 | /// # use histogram::Histogram; 500 | /// let mut h = Histogram::new(); 501 | /// 502 | /// h.increment_by(1, 1).unwrap(); 503 | /// h.increment_by(2, 2).unwrap(); 504 | /// h.decrement_by(1, 1).unwrap(); 505 | /// 506 | /// assert_eq!(h.get(2).unwrap(), 2); 507 | /// assert_eq!(h.get(1).unwrap(), 0); 508 | /// ``` 509 | pub fn decrement_by(&mut self, value: u64, count: u64) -> Result<(), HistogramError> { 510 | if value > self.config.max_value { 511 | if let Some(new_missed_large) = self.data.counters.missed_large.checked_sub(count) { 512 | self.data.counters.missed_large = new_missed_large; 513 | self.data.counters.entries_total = 514 | self.data.counters.entries_total.saturating_sub(count); 515 | Err(HistogramError::SampleValueTooLarge) 516 | } else { 517 | Err(HistogramError::SampleValueUnderflow) 518 | } 519 | } else { 520 | match self.get_index(value) { 521 | Some(index) => { 522 | if let Some(new_index_value) = self.data.data[index].checked_sub(count) { 523 | self.data.data[index] = new_index_value; 524 | self.data.counters.entries_total = 525 | self.data.counters.entries_total.saturating_sub(count); 526 | Ok(()) 527 | } else { 528 | Err(HistogramError::Underflow) 529 | } 530 | } 531 | None => { 532 | self.data.counters.missed_unknown = 533 | self.data.counters.missed_unknown.saturating_add(count); 534 | Err(HistogramError::SampleValueUnknown) 535 | } 536 | } 537 | } 538 | } 539 | 540 | /// get the count for a value 541 | /// 542 | /// # Example 543 | /// ``` 544 | /// # use histogram::Histogram; 545 | /// let mut h = Histogram::new(); 546 | /// assert_eq!(h.get(1).unwrap(), 0); 547 | /// ``` 548 | pub fn get(&self, value: u64) -> Option { 549 | match self.get_index(value) { 550 | Some(index) => Some(self.data.data[index]), 551 | None => None, 552 | } 553 | } 554 | 555 | /// calculate the index for a given value 556 | fn get_index(&self, value: u64) -> Option { 557 | if value <= (self.properties.linear_max + 2_u64.pow(self.config.precision)) { 558 | return Some(value as usize); 559 | } 560 | 561 | let l_max = self.properties.linear_max as u32; 562 | 563 | let outer = 63 - value.leading_zeros(); 564 | 565 | let l_power = 63 - self.properties.linear_max.leading_zeros(); 566 | 567 | let remain = value as f64 - 2.0_f64.powi(outer as i32); 568 | 569 | let inner = (f64::from(self.properties.buckets_inner) * remain as f64 / 570 | 2.0_f64.powi((outer) as i32)) 571 | .floor() as u32; 572 | 573 | // this gives the shifted outer index 574 | let outer = outer as u32 - l_power; 575 | 576 | let index = l_max + self.properties.buckets_inner * outer + inner + 1; 577 | 578 | Some(index as usize) 579 | } 580 | 581 | /// calculate the nominal value of the given index 582 | fn index_value(&self, index: usize) -> u64 { 583 | // in this case, the index is linear 584 | let index = index as u32; 585 | 586 | let linear_max = self.properties.linear_max as u32; 587 | 588 | if index <= linear_max { 589 | return u64::from(index); 590 | } 591 | 592 | let log_index = index - linear_max; 593 | 594 | let outer = (f64::from(log_index) / f64::from(self.properties.buckets_inner)).floor() as 595 | u32; 596 | 597 | let inner = log_index - outer * self.properties.buckets_inner as u32; 598 | 599 | let mut value = 2.0_f64.powi((outer as u32 + self.properties.linear_power) as i32); 600 | value += f64::from(inner) * (value as f64 / f64::from(self.properties.buckets_inner)); 601 | 602 | if value > self.config.max_value as f64 { 603 | return self.config.max_value as u64; 604 | } 605 | value.ceil() as u64 606 | } 607 | 608 | /// return the value for the given percentile 609 | /// 610 | /// # Example 611 | /// ``` 612 | /// # use histogram::Histogram; 613 | /// let mut h = Histogram::new(); 614 | /// for value in 1..1000 { 615 | /// h.increment(value).unwrap(); 616 | /// } 617 | /// 618 | /// assert_eq!(h.percentile(50.0).unwrap(), 501); 619 | /// assert_eq!(h.percentile(90.0).unwrap(), 901); 620 | /// assert_eq!(h.percentile(99.0).unwrap(), 991); 621 | /// assert_eq!(h.percentile(99.9).unwrap(), 999); 622 | /// ``` 623 | pub fn percentile(&self, percentile: f64) -> Result { 624 | if percentile < 0.0 || percentile > 100.0 { 625 | return Err(HistogramError::InvalidPercentileValue); 626 | } 627 | 628 | let total = self.try_entries()?; 629 | 630 | let mut need = (total as f64 * (percentile / 100.0_f64)).ceil() as u64; 631 | 632 | if need > total { 633 | need = total; 634 | } 635 | 636 | need = total - need; 637 | 638 | let mut index: isize = (self.buckets_total() - 1) as isize; 639 | let mut step: isize = -1 as isize; 640 | 641 | let mut have = if percentile < 50.0 { 642 | index = 0 as isize; 643 | step = 1 as isize; 644 | need = total - need; 645 | 0 646 | } else { 647 | self.data.counters.missed_large 648 | }; 649 | 650 | if need == 0 { 651 | need = 1; 652 | } 653 | 654 | if have >= need { 655 | if index == 0 { 656 | return Err(HistogramError::Underflow); 657 | } else { 658 | return Err(HistogramError::Overflow); 659 | } 660 | } 661 | 662 | loop { 663 | have += self.data.data[index as usize]; 664 | 665 | if have >= need { 666 | return Ok(self.index_value(index as usize) as u64); 667 | } 668 | 669 | index += step; 670 | 671 | if index >= self.buckets_total() as isize { 672 | break; 673 | } 674 | 675 | if index < 0 { 676 | break; 677 | } 678 | } 679 | 680 | Err(HistogramError::UnknownFailure) 681 | } 682 | 683 | /// return a set of quantiles based on the desired percentiles, provided as a slice 684 | /// 685 | /// # Example 686 | /// ``` 687 | /// # use histogram::Histogram; 688 | /// let mut h = Histogram::new(); 689 | /// 690 | /// for value in 1..1000 { 691 | /// h.increment(value).unwrap(); 692 | /// } 693 | /// 694 | /// let quantiles = h.quantile_vec(&vec![50.0, 90.0, 99.0, 99.9]).unwrap(); 695 | /// assert_eq!(quantiles, vec![501, 901, 991, 999]); 696 | /// ``` 697 | pub fn quantile_vec(&self, pcts: &[f64]) -> Result, HistogramError> { 698 | pcts.iter().map(|p| Ok(self.percentile(*p)?)).collect() 699 | } 700 | 701 | /// return the quartile values of the histogram as a 4-tuple 702 | /// 703 | /// # Example 704 | /// ``` 705 | /// # use histogram::Histogram; 706 | /// let mut h = Histogram::new(); 707 | /// 708 | /// for value in 1..1000 { 709 | /// h.increment(value).unwrap(); 710 | /// } 711 | /// 712 | /// let quantiles = h.quantile_vec(&vec![50.0, 90.0, 99.0, 99.9]).unwrap(); 713 | /// assert_eq!(quantiles, vec![501, 901, 991, 999]); 714 | /// ``` 715 | pub fn quartiles(&self) -> Result<(u64, u64, u64, u64), HistogramError> { 716 | Ok(( 717 | self.percentile(25.0)?, 718 | self.percentile(50.0)?, 719 | self.percentile(75.0)?, 720 | self.percentile(100.0)?, 721 | )) 722 | } 723 | 724 | /// return the quintile values of the histogram as a 5-tuple 725 | pub fn quintiles(&self) -> Result<(u64, u64, u64, u64, u64), HistogramError> { 726 | Ok(( 727 | self.percentile(20.0)?, 728 | self.percentile(40.0)?, 729 | self.percentile(60.0)?, 730 | self.percentile(80.0)?, 731 | self.percentile(100.0)?, 732 | )) 733 | } 734 | 735 | /// convenience function for min 736 | /// 737 | /// # Example 738 | /// ``` 739 | /// # use histogram::Histogram; 740 | /// let mut h = Histogram::new(); 741 | /// for value in 1..1000 { 742 | /// h.increment(value); 743 | /// } 744 | /// assert_eq!(h.minimum().unwrap(), 1); 745 | /// ``` 746 | pub fn minimum(&self) -> Result { 747 | self.percentile(0.0_f64) 748 | } 749 | 750 | /// convenience function for max 751 | /// 752 | /// # Example 753 | /// ``` 754 | /// # use histogram::Histogram; 755 | /// let mut h = Histogram::new(); 756 | /// for value in 1..1000 { 757 | /// h.increment(value); 758 | /// } 759 | /// assert_eq!(h.maximum().unwrap(), 999); 760 | /// ``` 761 | pub fn maximum(&self) -> Result { 762 | self.percentile(100.0_f64) 763 | } 764 | 765 | /// arithmetic mean approximation across the histogram, returning an integer 766 | /// 767 | /// # Example 768 | /// ``` 769 | /// # use histogram::Histogram; 770 | /// let mut h = Histogram::new(); 771 | /// for value in 1..1000 { 772 | /// h.increment(value); 773 | /// } 774 | /// assert_eq!(h.mean().unwrap(), 500); 775 | /// ``` 776 | pub fn mean(&self) -> Result { 777 | self.mean_f64().map(|n| n.ceil() as u64) 778 | } 779 | 780 | /// arithmetic mean approximation across the histogram, returning a float 781 | pub fn mean_f64(&self) -> Result { 782 | let total = self.try_entries()?; 783 | 784 | let mut mean = 0.0_f64; 785 | 786 | for index in 0..(self.buckets_total() as usize) { 787 | mean += (self.index_value(index) as f64 * self.data.data[index] as f64) as f64 / 788 | total as f64; 789 | } 790 | 791 | Ok(mean) 792 | } 793 | 794 | /// standard variance approximation across the histogram, returning an integer 795 | /// 796 | /// # Example 797 | /// ``` 798 | /// # use histogram::Histogram; 799 | /// let mut h = Histogram::new(); 800 | /// for value in 1..11 { 801 | /// h.increment(value); 802 | /// } 803 | /// assert_eq!(h.stdvar().unwrap(), 9); 804 | /// ``` 805 | pub fn stdvar(&self) -> Result { 806 | self.stdvar_f64().map(|n| n.ceil() as u64) 807 | } 808 | 809 | /// standard variance approximation across the histogram, returning a float 810 | pub fn stdvar_f64(&self) -> Result { 811 | let total = self.try_entries()? as f64; 812 | 813 | let m = self.mean_f64()?; 814 | 815 | let mut stdvar = 0.0_f64; 816 | 817 | for index in 0..(self.buckets_total() as usize) { 818 | let v = self.index_value(index) as f64; 819 | let c = self.data.data[index] as f64; 820 | stdvar += (c * v * v) - (2_f64 * c * m * v) + (c * m * m); 821 | } 822 | 823 | Ok(stdvar / total) 824 | } 825 | 826 | /// standard deviation approximation across the histogram, returning an integer 827 | /// 828 | /// # Example 829 | /// ``` 830 | /// # use histogram::Histogram; 831 | /// let mut h = Histogram::new(); 832 | /// 833 | /// for value in 1..11 { 834 | /// h.increment(value); 835 | /// } 836 | /// 837 | /// assert_eq!(h.stddev().unwrap(), 3); 838 | /// 839 | /// h.clear(); 840 | /// 841 | /// for value in 1..4 { 842 | /// h.increment(value); 843 | /// } 844 | /// for _ in 0..26 { 845 | /// h.increment(1); 846 | /// } 847 | /// 848 | /// assert_eq!(h.stddev().unwrap(), 1); 849 | /// ``` 850 | pub fn stddev(&self) -> Option { 851 | self.stdvar_f64().map(|n| n.sqrt().ceil() as u64).ok() 852 | } 853 | 854 | /// standard deviation approximation accross the histogram, returning a float 855 | pub fn stddev_f64(&self) -> Option { 856 | self.stdvar_f64().map(f64::sqrt).ok() 857 | } 858 | 859 | /// merge one Histogram into another Histogram 860 | /// 861 | /// # Example 862 | /// ``` 863 | /// # use histogram::Histogram; 864 | /// let mut a = Histogram::new(); 865 | /// let mut b = Histogram::new(); 866 | /// 867 | /// assert_eq!(a.entries(), 0); 868 | /// assert_eq!(b.entries(), 0); 869 | /// 870 | /// a.increment(1); 871 | /// b.increment(2); 872 | /// 873 | /// assert_eq!(a.entries(), 1); 874 | /// assert_eq!(b.entries(), 1); 875 | /// 876 | /// a.merge(&mut b); 877 | /// 878 | /// assert_eq!(a.entries(), 2); 879 | /// assert_eq!(a.get(1).unwrap(), 1); 880 | /// assert_eq!(a.get(2).unwrap(), 1); 881 | /// ``` 882 | pub fn merge(&mut self, other: &Histogram) { 883 | for bucket in other { 884 | let _ = self.increment_by(bucket.value, bucket.count); 885 | } 886 | } 887 | 888 | /// return the number of entries in the Histogram 889 | /// 890 | /// # Example 891 | /// ``` 892 | /// # use histogram::Histogram; 893 | /// let mut h = Histogram::new(); 894 | /// 895 | /// assert_eq!(h.entries(), 0); 896 | /// h.increment(1); 897 | /// assert_eq!(h.entries(), 1); 898 | /// ``` 899 | pub fn entries(&self) -> u64 { 900 | self.data.counters.entries_total 901 | } 902 | 903 | /// return the number of entries in the Histogram or a `NoData` error 904 | fn try_entries(&self) -> Result { 905 | match self.entries() { 906 | 0 => Err(HistogramError::NoData), 907 | n => Ok(n), 908 | } 909 | } 910 | 911 | /// return the number of buckets in the Histogram 912 | /// 913 | /// # Example 914 | /// ``` 915 | /// # use histogram::Histogram; 916 | /// let mut h = Histogram::new(); 917 | /// 918 | /// assert!(h.buckets_total() > 1); 919 | /// ``` 920 | pub fn buckets_total(&self) -> u64 { 921 | (self.get_index(self.config.max_value).unwrap() + 1) as u64 922 | } 923 | } 924 | 925 | #[cfg(test)] 926 | mod tests { 927 | use super::Histogram; 928 | 929 | #[test] 930 | fn test_too_large() { 931 | let h = Histogram::configure() 932 | .max_value(10_000) 933 | .precision(3) 934 | .max_memory(8192) 935 | .build(); 936 | 937 | if let Some(_) = h { 938 | panic!("Created histogram which used too much memory"); 939 | } 940 | } 941 | 942 | #[test] 943 | fn test_increment_0() { 944 | let mut h = Histogram::new(); 945 | 946 | for op in 1..1000000 { 947 | h.increment(1).unwrap(); 948 | assert_eq!(h.entries(), op); 949 | } 950 | } 951 | 952 | #[test] 953 | fn test_increment_1() { 954 | let mut h = Histogram::configure() 955 | .max_value(10) 956 | .precision(3) 957 | .build() 958 | .unwrap(); 959 | 960 | // increment values across the entire range 961 | // including 0 and max_value 962 | for v in 0..11 { 963 | h.increment(v).unwrap(); 964 | assert_eq!(h.entries(), v + 1); 965 | } 966 | } 967 | 968 | #[test] 969 | fn test_decrement_0() { 970 | let mut h = Histogram::new(); 971 | let m = 1000000; 972 | 973 | for _ in 0..m { 974 | h.increment(2).unwrap(); 975 | } 976 | 977 | for op in 1..m { 978 | h.decrement(2).unwrap(); 979 | assert_eq!(h.entries(), m - op); 980 | } 981 | } 982 | 983 | #[test] 984 | fn test_decrement_1() { 985 | let mut h = Histogram::configure() 986 | .max_value(20_000) 987 | .precision(3) 988 | .build() 989 | .unwrap(); 990 | 991 | let v = h.properties.linear_max + 2; 992 | let m = 1_000_000; 993 | 994 | for _ in 0..m { 995 | h.increment(v).unwrap(); 996 | } 997 | 998 | for op in 1..m { 999 | h.decrement(v).unwrap(); 1000 | assert_eq!(h.entries(), m - op); 1001 | } 1002 | } 1003 | 1004 | #[test] 1005 | #[should_panic(expected = "SampleValueUnderflow")] 1006 | fn test_decrement_4() { 1007 | let mut h = Histogram::new(); 1008 | let v = h.config.max_value + 1; 1009 | h.decrement(v).unwrap(); 1010 | } 1011 | 1012 | #[test] 1013 | #[should_panic(expected = "SampleValueTooLarge")] 1014 | fn test_decrement_5() { 1015 | let mut h = Histogram::new(); 1016 | let v = h.config.max_value + 1; 1017 | let _ = h.increment(v); 1018 | h.decrement(v).unwrap(); 1019 | } 1020 | 1021 | #[test] 1022 | fn test_decrement_example_0() { 1023 | let mut h = Histogram::new(); 1024 | 1025 | h.increment(1).unwrap(); 1026 | assert_eq!(h.get(1).unwrap(), 1); 1027 | h.decrement(1).unwrap(); 1028 | assert_eq!(h.get(1).unwrap(), 0); 1029 | } 1030 | 1031 | #[test] 1032 | fn test_decrement_by_example_0() { 1033 | let mut h = Histogram::new(); 1034 | 1035 | h.increment_by(1, 1).unwrap(); 1036 | h.increment_by(2, 2).unwrap(); 1037 | h.decrement_by(1, 1).unwrap(); 1038 | 1039 | assert_eq!(h.get(2).unwrap(), 2); 1040 | assert_eq!(h.get(1).unwrap(), 0); 1041 | } 1042 | 1043 | #[test] 1044 | fn test_get() { 1045 | let mut h = Histogram::new(); 1046 | 1047 | h.increment(1).unwrap(); 1048 | assert_eq!(h.get(1), Some(1)); 1049 | 1050 | h.increment(1).unwrap(); 1051 | assert_eq!(h.get(1), Some(2)); 1052 | 1053 | h.increment(2).unwrap(); 1054 | assert_eq!(h.get(2), Some(1)); 1055 | 1056 | assert_eq!(h.get(3), Some(0)); 1057 | } 1058 | 1059 | #[test] 1060 | fn test_get_index_0() { 1061 | let h = Histogram::configure() 1062 | .max_value(32) 1063 | .precision(3) 1064 | .build() 1065 | .unwrap(); 1066 | 1067 | // all values should index directly to value 1068 | // no estimated buckets are needed given the precision and max 1069 | for i in 0..32 { 1070 | assert_eq!(h.get_index(i), Some(i as usize)); 1071 | assert_eq!(h.index_value(i as usize), i); 1072 | } 1073 | } 1074 | 1075 | #[test] 1076 | fn test_index_value_0() { 1077 | let h = Histogram::configure() 1078 | .max_value(100) 1079 | .precision(1) 1080 | .build() 1081 | .unwrap(); 1082 | 1083 | assert_eq!(h.index_value(1), 1); 1084 | assert_eq!(h.index_value(2), 2); 1085 | assert_eq!(h.index_value(15), 15); 1086 | 1087 | assert_eq!(h.index_value(16), 16); 1088 | assert_eq!(h.index_value(26), 32); 1089 | assert_eq!(h.index_value(36), 64); 1090 | } 1091 | 1092 | #[test] 1093 | fn test_index_value_1() { 1094 | let h = Histogram::configure() 1095 | .max_value(1_000) 1096 | .precision(2) 1097 | .build() 1098 | .unwrap(); 1099 | 1100 | assert_eq!(h.index_value(0), 0); 1101 | assert_eq!(h.index_value(1), 1); 1102 | assert_eq!(h.index_value(126), 126); 1103 | 1104 | assert_eq!(h.index_value(128), 128); 1105 | assert_eq!(h.index_value(228), 256); 1106 | assert_eq!(h.index_value(328), 512); 1107 | } 1108 | 1109 | #[test] 1110 | fn test_index_value_2() { 1111 | let h = Histogram::configure() 1112 | .max_value(10_000) 1113 | .precision(3) 1114 | .build() 1115 | .unwrap(); 1116 | 1117 | assert_eq!(h.index_value(0), 0); 1118 | assert_eq!(h.index_value(1), 1); 1119 | assert_eq!(h.index_value(1023), 1023); 1120 | 1121 | assert_eq!(h.index_value(1024), 1024); 1122 | assert_eq!(h.index_value(2024), 2048); 1123 | } 1124 | 1125 | #[test] 1126 | fn test_iterator() { 1127 | let h = Histogram::configure() 1128 | .max_value(100) 1129 | .precision(1) 1130 | .build() 1131 | .unwrap(); 1132 | 1133 | let mut buckets_seen = 0; 1134 | for bucket in &h { 1135 | println!("Bucket: {:?}", bucket); 1136 | assert_eq!(bucket.id(), buckets_seen); 1137 | assert_eq!(bucket.value(), h.index_value(bucket.id() as usize)); 1138 | assert_eq!(bucket.count(), 0); 1139 | buckets_seen += 1; 1140 | } 1141 | assert_eq!(h.buckets_total(), buckets_seen); 1142 | } 1143 | 1144 | #[test] 1145 | fn test_percentile() { 1146 | let mut h = Histogram::configure() 1147 | .max_value(1_000) 1148 | .precision(4) 1149 | .build() 1150 | .unwrap(); 1151 | 1152 | for i in 100..200 { 1153 | h.increment(i).ok().expect("error"); 1154 | } 1155 | 1156 | assert_eq!(h.percentile(0.0).unwrap(), 100); 1157 | assert_eq!(h.percentile(10.0).unwrap(), 109); 1158 | assert_eq!(h.percentile(25.0).unwrap(), 124); 1159 | assert_eq!(h.percentile(50.0).unwrap(), 150); 1160 | assert_eq!(h.percentile(75.0).unwrap(), 175); 1161 | assert_eq!(h.percentile(90.0).unwrap(), 190); 1162 | assert_eq!(h.percentile(95.0).unwrap(), 195); 1163 | assert_eq!(h.percentile(100.0).unwrap(), 199); 1164 | } 1165 | 1166 | #[test] 1167 | fn test_quantile_vec() { 1168 | let mut h = Histogram::configure() 1169 | .max_value(1_000) 1170 | .precision(4) 1171 | .build() 1172 | .unwrap(); 1173 | 1174 | for i in 100..200 { 1175 | h.increment(i).ok().expect("error"); 1176 | } 1177 | 1178 | let pct = vec![0.0, 10.0, 25.0, 50.0, 75.0, 90.0, 95.0, 100.0]; 1179 | let percentiles = h.quantile_vec(&pct).unwrap(); 1180 | 1181 | assert_eq!(percentiles.len(), 8); 1182 | assert_eq!(percentiles[0], 100); 1183 | assert_eq!(percentiles[1], 109); 1184 | assert_eq!(percentiles[2], 124); 1185 | assert_eq!(percentiles[3], 150); 1186 | assert_eq!(percentiles[4], 175); 1187 | assert_eq!(percentiles[5], 190); 1188 | assert_eq!(percentiles[6], 195); 1189 | assert_eq!(percentiles[7], 199); 1190 | } 1191 | 1192 | #[test] 1193 | fn test_quartiles() { 1194 | let mut h = Histogram::configure() 1195 | .max_value(1_000) 1196 | .precision(4) 1197 | .build() 1198 | .unwrap(); 1199 | 1200 | for i in 100..200 { 1201 | h.increment(i).ok().expect("error"); 1202 | } 1203 | 1204 | let quartiles = h.quartiles().unwrap(); 1205 | assert_eq!(quartiles.0, 124); 1206 | assert_eq!(quartiles.1, 150); 1207 | assert_eq!(quartiles.2, 175); 1208 | assert_eq!(quartiles.3, 199); 1209 | } 1210 | 1211 | #[test] 1212 | fn test_quintiles() { 1213 | let mut h = Histogram::configure() 1214 | .max_value(1_000) 1215 | .precision(4) 1216 | .build() 1217 | .unwrap(); 1218 | 1219 | for i in 100..200 { 1220 | h.increment(i).ok().expect("error"); 1221 | } 1222 | 1223 | let qvec = h.quantile_vec(&vec![20.0, 40.0, 60.0, 80.0, 100.0]) 1224 | .unwrap(); 1225 | let quintiles = h.quintiles().unwrap(); 1226 | assert_eq!(quintiles.0, qvec[0]); 1227 | assert_eq!(quintiles.1, qvec[1]); 1228 | assert_eq!(quintiles.2, qvec[2]); 1229 | assert_eq!(quintiles.3, qvec[3]); 1230 | assert_eq!(quintiles.4, qvec[4]); 1231 | } 1232 | 1233 | #[test] 1234 | fn test_percentile_bad() { 1235 | let mut h = Histogram::configure() 1236 | .max_value(1_000) 1237 | .precision(4) 1238 | .build() 1239 | .unwrap(); 1240 | 1241 | let _ = h.increment(5_000); 1242 | 1243 | assert!(h.percentile(0.0).is_err()); 1244 | assert!(h.percentile(50.0).is_err()); 1245 | assert!(h.percentile(100.0).is_err()); 1246 | 1247 | let _ = h.increment(1); 1248 | 1249 | assert!(h.percentile(0.0).is_ok()); 1250 | 1251 | let _ = h.increment(500); 1252 | let _ = h.increment(500); 1253 | 1254 | assert!(h.percentile(50.0).is_ok()); 1255 | } 1256 | 1257 | #[test] 1258 | fn test_width_1() { 1259 | let mut h = Histogram::configure() 1260 | .max_value(100) 1261 | .precision(3) 1262 | .build() 1263 | .unwrap(); 1264 | 1265 | for v in 0..101 { 1266 | let _ = h.increment(v); 1267 | } 1268 | 1269 | assert_eq!(h.data.counters.missed_large, 0); 1270 | 1271 | let mut prev_id = 0; 1272 | for b in &h { 1273 | println!("Bucket: {:?}", b); 1274 | if b.id() >= 1 { 1275 | assert!(b.id() - 1 == prev_id); 1276 | prev_id = b.id(); 1277 | } 1278 | assert!(b.width() != 0, "width should not be 0"); 1279 | assert_eq!(b.width(), b.count()); 1280 | } 1281 | } 1282 | 1283 | #[test] 1284 | fn test_width_2() { 1285 | let mut h = Histogram::configure() 1286 | .max_value(1000) 1287 | .precision(2) 1288 | .build() 1289 | .unwrap(); 1290 | 1291 | for v in 0..1001 { 1292 | let _ = h.increment(v); 1293 | } 1294 | 1295 | assert_eq!(h.data.counters.missed_large, 0); 1296 | 1297 | let mut prev_id = 0; 1298 | let mut prev_value = 0; 1299 | for b in &h { 1300 | println!("Bucket: {:?}", b); 1301 | if b.id() >= 1 { 1302 | assert_eq!(b.width(), b.value() - prev_value); 1303 | assert!(b.id() - 1 == prev_id); 1304 | prev_id = b.id(); 1305 | prev_value = b.value(); 1306 | } 1307 | assert!(b.width() != 0, "width should not be 0"); 1308 | } 1309 | } 1310 | 1311 | #[test] 1312 | fn test_width_3() { 1313 | let mut h = Histogram::configure() 1314 | .max_value(10_000) 1315 | .precision(3) 1316 | .build() 1317 | .unwrap(); 1318 | 1319 | for v in 0..10_000 { 1320 | let _ = h.increment(v + 1); 1321 | } 1322 | 1323 | assert_eq!(h.data.counters.missed_large, 0); 1324 | 1325 | let mut prev_id = 0; 1326 | let mut prev_value = 0; 1327 | for b in &h { 1328 | println!("Bucket: {:?}", b); 1329 | if b.id() >= 1 { 1330 | assert_eq!(b.width(), b.value() - prev_value); 1331 | assert!(b.id() - 1 == prev_id); 1332 | prev_id = b.id(); 1333 | prev_value = b.value(); 1334 | } 1335 | assert!(b.width() != 0, "width should not be 0"); 1336 | } 1337 | } 1338 | 1339 | #[test] 1340 | #[should_panic(expected = "InvalidPercentileValue")] 1341 | fn test_invalid_percentile_1() { 1342 | let mut h = Histogram::new(); 1343 | h.increment(1).unwrap(); 1344 | h.percentile(-1.0).unwrap(); 1345 | } 1346 | 1347 | #[test] 1348 | #[should_panic(expected = "InvalidPercentileValue")] 1349 | fn test_invalid_percentile_2() { 1350 | let mut h = Histogram::new(); 1351 | h.increment(1).unwrap(); 1352 | h.percentile(101.0).unwrap(); 1353 | } 1354 | 1355 | #[test] 1356 | fn test_valid_percentile_1() { 1357 | let mut h = Histogram::new(); 1358 | h.increment(1).unwrap(); 1359 | assert_eq!(h.percentile(100.0).unwrap(), 1); 1360 | } 1361 | 1362 | #[test] 1363 | fn test_valid_percentile_2() { 1364 | let mut h = Histogram::new(); 1365 | h.increment(1).unwrap(); 1366 | assert_eq!(h.percentile(0.0).unwrap(), 1); 1367 | } 1368 | } 1369 | --------------------------------------------------------------------------------