blob: 3f19af27cc5dfe11087c460a184bfd4460595f4a [file] [log] [blame]
mtklein90c471e2014-06-16 14:04:32 -07001#ifndef Stats_DEFINED
2#define Stats_DEFINED
3
mtklein5d9d10e2014-07-11 11:57:07 -07004#include <math.h>
5
6#include "SkString.h"
mtklein40b32be2014-07-09 08:46:49 -07007#include "SkTSort.h"
8
mtklein5d9d10e2014-07-11 11:57:07 -07009static const char* kBars[] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
10
mtklein90c471e2014-06-16 14:04:32 -070011struct Stats {
12 Stats(const double samples[], int n) {
13 min = samples[0];
14 max = samples[0];
15 for (int i = 0; i < n; i++) {
16 if (samples[i] < min) { min = samples[i]; }
17 if (samples[i] > max) { max = samples[i]; }
18 }
19
20 double sum = 0.0;
21 for (int i = 0 ; i < n; i++) {
22 sum += samples[i];
23 }
24 mean = sum / n;
25
26 double err = 0.0;
27 for (int i = 0 ; i < n; i++) {
28 err += (samples[i] - mean) * (samples[i] - mean);
29 }
30 var = err / (n-1);
mtklein40b32be2014-07-09 08:46:49 -070031
32 SkAutoTMalloc<double> sorted(n);
33 memcpy(sorted.get(), samples, n * sizeof(double));
34 SkTQSort(sorted.get(), sorted.get() + n - 1);
35 median = sorted[n/2];
mtklein5d9d10e2014-07-11 11:57:07 -070036
mtkleina189ccd2014-07-14 12:28:47 -070037 // Normalize samples to [min, max] in as many quanta as we have distinct bars to print.
mtklein5d9d10e2014-07-11 11:57:07 -070038 for (int i = 0; i < n; i++) {
mtkleina189ccd2014-07-14 12:28:47 -070039 if (min == max) {
40 // All samples are the same value. Don't divide by zero.
41 plot.append(kBars[0]);
42 continue;
43 }
44
mtklein5d9d10e2014-07-11 11:57:07 -070045 double s = samples[i];
mtklein5d9d10e2014-07-11 11:57:07 -070046 s -= min;
47 s /= (max - min);
48 s *= (SK_ARRAY_COUNT(kBars) - 1);
49 const size_t bar = (size_t)round(s);
50 SK_ALWAYSBREAK(bar < SK_ARRAY_COUNT(kBars));
51 plot.append(kBars[bar]);
52 }
mtklein90c471e2014-06-16 14:04:32 -070053 }
54
55 double min;
56 double max;
mtklein5d9d10e2014-07-11 11:57:07 -070057 double mean; // Estimate of population mean.
58 double var; // Estimate of population variance.
mtklein40b32be2014-07-09 08:46:49 -070059 double median;
mtklein5d9d10e2014-07-11 11:57:07 -070060 SkString plot; // A single-line bar chart (_not_ histogram) of the samples.
mtklein90c471e2014-06-16 14:04:32 -070061};
62
63#endif//Stats_DEFINED