2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef FOLLY_STATS_MULTILEVELTIMESERIES_H_
18 #define FOLLY_STATS_MULTILEVELTIMESERIES_H_
24 #include <glog/logging.h>
25 #include "folly/stats/BucketedTimeSeries.h"
30 * This class represents a timeseries which keeps several levels of data
31 * granularity (similar in principle to the loads reported by the UNIX
32 * 'uptime' command). It uses several instances (one per level) of
33 * BucketedTimeSeries as the underlying storage.
35 * This can easily be used to track sums (and thus rates or averages) over
36 * several predetermined time periods, as well as all-time sums. For example,
37 * you would use to it to track query rate or response speed over the last
38 * 5, 15, 30, and 60 minutes.
40 * The MultiLevelTimeSeries takes a list of level durations as an input; the
41 * durations must be strictly increasing. Furthermore a special level can be
42 * provided with a duration of '0' -- this will be an "all-time" level. If
43 * an all-time level is provided, it MUST be the last level present.
45 * The class assumes that time advances forward -- you can't retroactively add
46 * values for events in the past -- the 'now' argument is provided for better
47 * efficiency and ease of unittesting.
49 * The class is not thread-safe -- use your own synchronization!
51 template <typename VT, typename TT=std::chrono::seconds>
52 class MultiLevelTimeSeries {
56 typedef folly::BucketedTimeSeries<ValueType, TimeType> Level;
59 * Create a new MultiLevelTimeSeries.
61 * This creates a new MultiLevelTimeSeries that tracks time series data at the
62 * specified time durations (level). The time series data tracked at each
63 * level is then further divided by numBuckets for memory efficiency.
65 * The durations must be strictly increasing. Furthermore a special level can
66 * be provided with a duration of '0' -- this will be an "all-time" level. If
67 * an all-time level is provided, it MUST be the last level present.
69 MultiLevelTimeSeries(size_t numBuckets,
71 const TimeType levelDurations[]);
74 * Return the number of buckets used to track time series at each level.
76 size_t numBuckets() const { return numBuckets_; }
79 * Return the number of levels tracked by MultiLevelTimeSeries.
81 size_t numLevels() const { return levels_.size(); }
84 * Get the BucketedTimeSeries backing the specified level.
86 * Note: you should generally call update() or flush() before accessing the
87 * data. Otherwise you may be reading stale data if update() or flush() has
88 * not been called recently.
90 const Level& getLevel(int level) const {
92 CHECK_LT(level, levels_.size());
93 return levels_[level];
97 * Get the highest granularity level that is still large enough to contain
98 * data going back to the specified start time.
100 * Note: you should generally call update() or flush() before accessing the
101 * data. Otherwise you may be reading stale data if update() or flush() has
102 * not been called recently.
104 const Level& getLevel(TimeType start) const {
105 for (const auto& level : levels_) {
106 if (level.isAllTime()) {
109 // Note that we use duration() here rather than elapsed().
110 // If duration is large enough to contain the start time then this level
111 // is good enough, even if elapsed() indicates that no data was recorded
112 // before the specified start time.
113 if (level.getLatestTime() - level.duration() <= start) {
117 // We should always have an all-time level, so this is never reached.
118 LOG(FATAL) << "No level of timeseries covers internval"
119 << " from " << start.count() << " to now";
120 return levels_.back();
124 * Return the sum of all the data points currently tracked at this level.
126 * Note: you should generally call update() or flush() before accessing the
127 * data. Otherwise you may be reading stale data if update() or flush() has
128 * not been called recently.
130 ValueType sum(int level) const {
131 return getLevel(level).sum();
135 * Return the average (sum / count) of all the data points currently tracked
138 * The return type may be specified to control whether floating-point or
139 * integer division should be performed.
141 * Note: you should generally call update() or flush() before accessing the
142 * data. Otherwise you may be reading stale data if update() or flush() has
143 * not been called recently.
145 template <typename ReturnType=double>
146 ReturnType avg(int level) const {
147 return getLevel(level).template avg<ReturnType>();
151 * Return the rate (sum divided by elaspsed time) of the all data points
152 * currently tracked at this level.
154 * Note: you should generally call update() or flush() before accessing the
155 * data. Otherwise you may be reading stale data if update() or flush() has
156 * not been called recently.
158 template <typename ReturnType=double, typename Interval=TimeType>
159 ValueType rate(int level) const {
160 return getLevel(level).template rate<ReturnType, Interval>();
164 * Return the number of data points currently tracked at this level.
166 * Note: you should generally call update() or flush() before accessing the
167 * data. Otherwise you may be reading stale data if update() or flush() has
168 * not been called recently.
170 int64_t count(int level) const {
171 return getLevel(level).count();
175 * Return the count divided by the elapsed time tracked at this level.
177 * Note: you should generally call update() or flush() before accessing the
178 * data. Otherwise you may be reading stale data if update() or flush() has
179 * not been called recently.
181 template <typename ReturnType=double, typename Interval=TimeType>
182 ReturnType countRate(int level) const {
183 return getLevel(level).template countRate<ReturnType, Interval>();
187 * Estimate the sum of the data points that occurred in the specified time
188 * period at this level.
190 * The range queried is [start, end).
191 * That is, start is inclusive, and end is exclusive.
193 * Note that data outside of the timeseries duration will no longer be
194 * available for use in the estimation. Specifying a start time earlier than
195 * getEarliestTime() will not have much effect, since only data points after
196 * that point in time will be counted.
198 * Note that the value returned is an estimate, and may not be precise.
200 * Note: you should generally call update() or flush() before accessing the
201 * data. Otherwise you may be reading stale data if update() or flush() has
202 * not been called recently.
204 ValueType sum(TimeType start, TimeType end) const {
205 return getLevel(start).sum(start, end);
209 * Estimate the average value during the specified time period.
211 * The same caveats documented in the sum(TimeType start, TimeType end)
212 * comments apply here as well.
214 * Note: you should generally call update() or flush() before accessing the
215 * data. Otherwise you may be reading stale data if update() or flush() has
216 * not been called recently.
218 template <typename ReturnType=double>
219 ReturnType avg(TimeType start, TimeType end) const {
220 return getLevel(start).template avg<ReturnType>(start, end);
224 * Estimate the rate during the specified time period.
226 * The same caveats documented in the sum(TimeType start, TimeType end)
227 * comments apply here as well.
229 * Note: you should generally call update() or flush() before accessing the
230 * data. Otherwise you may be reading stale data if update() or flush() has
231 * not been called recently.
233 template <typename ReturnType=double>
234 ReturnType rate(TimeType start, TimeType end) const {
235 return getLevel(start).template rate<ReturnType>(start, end);
239 * Estimate the count during the specified time period.
241 * The same caveats documented in the sum(TimeType start, TimeType end)
242 * comments apply here as well.
244 * Note: you should generally call update() or flush() before accessing the
245 * data. Otherwise you may be reading stale data if update() or flush() has
246 * not been called recently.
248 int64_t count(TimeType start, TimeType end) const {
249 return getLevel(start).count(start, end);
253 * Adds the value 'val' at time 'now' to all levels.
255 * Data points added at the same time point is cached internally here and not
256 * propagated to the underlying levels until either flush() is called or when
257 * update from a different time comes.
259 * This function expects time to always move forwards: it cannot be used to
260 * add historical data points that have occurred in the past. If now is
261 * older than the another timestamp that has already been passed to
262 * addValue() or update(), now will be ignored and the latest timestamp will
265 void addValue(TimeType now, const ValueType& val);
268 * Adds the value 'val' at time 'now' to all levels.
270 void addValue(TimeType now, const ValueType& val, int64_t times);
273 * Adds the value 'val' at time 'now' to all levels as the sum of 'nsamples'
276 void addValueAggregated(TimeType now, const ValueType& sum, int64_t nsamples);
279 * Update all the levels to the specified time, doing all the necessary
280 * work to rotate the buckets and remove any stale data points.
282 * When reading data from the timeseries, you should make sure to manually
283 * call update() before accessing the data. Otherwise you may be reading
284 * stale data if update() has not been called recently.
286 void update(TimeType now);
289 * Reset all the timeseries to an empty state as if no data points have ever
295 * Flush all cached updates.
301 std::vector<Level> levels_;
303 // Updates within the same time interval are cached
304 // They are flushed out when updates from a different time comes,
305 // or flush() is called.
306 TimeType cachedTime_;
307 ValueType cachedSum_;
313 #endif // FOLLY_STATS_MULTILEVELTIMESERIES_H_