Metric.cpp revision ec87e5c098f1ce1c9182d1c5438e0beca0996597
1//===-- Metric.cpp ----------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Metric.h"
11#include "MemoryGauge.h"
12#include <cmath>
13
14using namespace lldb_perf;
15
16template <class T>
17Metric<T>::Metric () : Metric ("")
18{
19}
20
21template <class T>
22Metric<T>::Metric (const char* n, const char* d) :
23    m_name(n ? n : ""),
24    m_description(d ? d : ""),
25    m_dataset ()
26{
27}
28
29template <class T>
30void
31Metric<T>::Append (T v)
32{
33    m_dataset.push_back(v);
34}
35
36template <class T>
37size_t
38Metric<T>::GetCount () const
39{
40    return m_dataset.size();
41}
42
43template <class T>
44T
45Metric<T>::GetSum () const
46{
47    T sum = 0;
48    for (auto v : m_dataset)
49        sum += v;
50    return sum;
51}
52
53template <class T>
54T
55Metric<T>::GetAverage () const
56{
57    return GetSum()/GetCount();
58}
59
60
61// Knuth's algorithm for stddev - massive cancellation resistant
62template <class T>
63T
64Metric<T>::GetStandardDeviation (StandardDeviationMode mode) const
65{
66    size_t n = 0;
67    T mean = 0;
68    T M2 = 0;
69    for (auto x : m_dataset)
70    {
71        n = n + 1;
72        T delta = x - mean;
73        mean = mean + delta/n;
74        M2 = M2+delta*(x-mean);
75    }
76    T variance;
77    if (mode == StandardDeviationMode::ePopulation || n == 1)
78        variance = M2 / n;
79    else
80        variance = M2 / (n - 1);
81    return sqrt(variance);
82}
83
84template class lldb_perf::Metric<double>;
85template class lldb_perf::Metric<MemoryStats>;
86