1/*
2 * Copyright 2012, The Android Open Source Project
3 *
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
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "TimeSeries.h"
18
19#include <math.h>
20#include <string.h>
21
22namespace android {
23
24TimeSeries::TimeSeries()
25    : mCount(0),
26      mSum(0.0) {
27}
28
29void TimeSeries::add(double val) {
30    if (mCount < kHistorySize) {
31        mValues[mCount++] = val;
32        mSum += val;
33    } else {
34        mSum -= mValues[0];
35        memmove(&mValues[0], &mValues[1], (kHistorySize - 1) * sizeof(double));
36        mValues[kHistorySize - 1] = val;
37        mSum += val;
38    }
39}
40
41double TimeSeries::mean() const {
42    if (mCount < 1) {
43        return 0.0;
44    }
45
46    return mSum / mCount;
47}
48
49double TimeSeries::sdev() const {
50    if (mCount < 1) {
51        return 0.0;
52    }
53
54    double m = mean();
55
56    double sum = 0.0;
57    for (size_t i = 0; i < mCount; ++i) {
58        double tmp = mValues[i] - m;
59        tmp *= tmp;
60
61        sum += tmp;
62    }
63
64    return sqrt(sum / mCount);
65}
66
67}  // namespace android
68