summaryrefslogtreecommitdiffstats
path: root/nserver/src/stats.c
blob: 6b99e7e5644670f9bca50f88c9b28996968c70a4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <math.h>
#include <stats.h>
#include <stdlib.h>
#include <dbg.h>

Stats *Stats_recreate(double sum, double sumsq, unsigned long n,
                      double min, double max)
{
    Stats *st  = malloc(sizeof(Stats));
    check_mem(st);

    st->sum =  sum;
    st->sumsq = sumsq;
    st->n  = n;
    st->min = min;
    st->max = max;

    return st;

 error:
    return NULL;
}

Stats *Stats_create()
{
    return Stats_recreate(0.0, 0.0, 0L, 0.0, 0.0);
}

void Stats_sample(Stats *st, double s)
{
    st->sum  += s;
    st->sumsq += s * s;

    if (st->n == 0) {
        st->min = s;
        st->max = s;
    } else {
        if (st->min > s)
            st->min = s;
        if (st->max < s)
            st->max = s;
    }

    st->n += 1;
}

char *Stats_dump(Stats *st)
{
    size_t char_sz = sizeof(char);
    size_t dstr_len = 280 * char_sz;

    // allocate space for dump string.
    char *dstr = calloc(dstr_len, char_sz);
    check_mem(dstr);

    // dump into dump str.
    int rc = snprintf(dstr, dstr_len,
                      "sum: %f, sumsq: %f, n: %ld, "
                      "min: %f, max: %f, mean: %f, stddev: %f",
                      st->sum, st->sumsq, st->n, st->min, st->max,
                      Stats_mean(st), Stats_stddev(st));
    check(rc > 0, "stats dump failed");

    return dstr;
 error:
    return NULL;
}