Home | History | Annotate | Download | only in base
      1 // Copyright 2014 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include <cmath>
      6 
      7 #include "cc/base/rolling_time_delta_history.h"
      8 
      9 namespace cc {
     10 
     11 RollingTimeDeltaHistory::RollingTimeDeltaHistory(size_t max_size)
     12     : max_size_(max_size) {}
     13 
     14 RollingTimeDeltaHistory::~RollingTimeDeltaHistory() {}
     15 
     16 void RollingTimeDeltaHistory::InsertSample(base::TimeDelta time) {
     17   if (max_size_ == 0)
     18     return;
     19 
     20   if (sample_set_.size() == max_size_) {
     21     sample_set_.erase(chronological_sample_deque_.front());
     22     chronological_sample_deque_.pop_front();
     23   }
     24 
     25   TimeDeltaMultiset::iterator it = sample_set_.insert(time);
     26   chronological_sample_deque_.push_back(it);
     27 }
     28 
     29 void RollingTimeDeltaHistory::Clear() {
     30   chronological_sample_deque_.clear();
     31   sample_set_.clear();
     32 }
     33 
     34 base::TimeDelta RollingTimeDeltaHistory::Percentile(double percent) const {
     35   if (sample_set_.size() == 0)
     36     return base::TimeDelta();
     37 
     38   double fraction = percent / 100.0;
     39 
     40   if (fraction <= 0.0)
     41     return *(sample_set_.begin());
     42 
     43   if (fraction >= 1.0)
     44     return *(sample_set_.rbegin());
     45 
     46   size_t num_smaller_samples =
     47       static_cast<size_t>(std::ceil(fraction * sample_set_.size())) - 1;
     48 
     49   if (num_smaller_samples > sample_set_.size() / 2) {
     50     size_t num_larger_samples = sample_set_.size() - num_smaller_samples - 1;
     51     TimeDeltaMultiset::const_reverse_iterator it = sample_set_.rbegin();
     52     for (size_t i = 0; i < num_larger_samples; i++)
     53       it++;
     54     return *it;
     55   }
     56 
     57   TimeDeltaMultiset::const_iterator it = sample_set_.begin();
     58   for (size_t i = 0; i < num_smaller_samples; i++)
     59     it++;
     60   return *it;
     61 }
     62 
     63 }  // namespace cc
     64