blob: ac077348e67d5b3f9bcfbaa0c9fbcc5ef5c72c0b [file] [log] [blame]
Artem Titove4ed6ea2019-01-11 11:02:19 +01001/*
2 * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "rtc_base/numerics/samples_stats_counter.h"
12
13#include <algorithm>
14#include <cmath>
15
16namespace webrtc {
17
18SamplesStatsCounter::SamplesStatsCounter() = default;
19SamplesStatsCounter::~SamplesStatsCounter() = default;
20SamplesStatsCounter::SamplesStatsCounter(SamplesStatsCounter&) = default;
21SamplesStatsCounter::SamplesStatsCounter(SamplesStatsCounter&&) = default;
22
23void SamplesStatsCounter::AddSample(double value) {
24 samples_.push_back(value);
25 sorted_ = false;
26 if (value > max_) {
27 max_ = value;
28 }
29 if (value < min_) {
30 min_ = value;
31 }
32 sum_ += value;
33}
34
35double SamplesStatsCounter::GetPercentile(double percentile) {
36 RTC_DCHECK(!IsEmpty());
37 RTC_CHECK_GE(percentile, 0);
38 RTC_CHECK_LE(percentile, 1);
39 if (!sorted_) {
40 std::sort(samples_.begin(), samples_.end());
41 sorted_ = true;
42 }
43 const double raw_rank = percentile * (samples_.size() - 1);
44 double int_part;
45 double fract_part = std::modf(raw_rank, &int_part);
46 size_t rank = static_cast<size_t>(int_part);
47 if (fract_part >= 1.0) {
48 // It can happen due to floating point calculation error.
49 rank++;
50 fract_part -= 1.0;
51 }
52
53 RTC_DCHECK_GE(rank, 0);
54 RTC_DCHECK_LT(rank, samples_.size());
55 RTC_DCHECK_GE(fract_part, 0);
56 RTC_DCHECK_LT(fract_part, 1);
57 RTC_DCHECK(rank + fract_part == raw_rank);
58
59 const double low = samples_[rank];
60 const double high = samples_[std::min(rank + 1, samples_.size() - 1)];
61 return low + fract_part * (high - low);
62}
63
64} // namespace webrtc