1 /*
2  * Copyright 2015 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef Stats_DEFINED
9 #define Stats_DEFINED
10 
11 #include "SkFloatingPoint.h"
12 #include "SkString.h"
13 #include "SkTSort.h"
14 
15 #ifdef SK_BUILD_FOR_WIN
16     static const char* kBars[] = { ".", "o", "O" };
17 #else
18     static const char* kBars[] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
19 #endif
20 
21 struct Stats {
StatsStats22     Stats(const SkTArray<double>& samples, bool want_plot) {
23         int n = samples.count();
24         if (!n) {
25             min = max = mean = var = median = 0;
26             return;
27         }
28 
29         min = samples[0];
30         max = samples[0];
31         for (int i = 0; i < n; i++) {
32             if (samples[i] < min) { min = samples[i]; }
33             if (samples[i] > max) { max = samples[i]; }
34         }
35 
36         double sum = 0.0;
37         for (int i = 0 ; i < n; i++) {
38             sum += samples[i];
39         }
40         mean = sum / n;
41 
42         double err = 0.0;
43         for (int i = 0 ; i < n; i++) {
44             err += (samples[i] - mean) * (samples[i] - mean);
45         }
46         var = sk_ieee_double_divide(err, n-1);
47 
48         SkAutoTMalloc<double> sorted(n);
49         memcpy(sorted.get(), samples.begin(), n * sizeof(double));
50         SkTQSort(sorted.get(), sorted.get() + n - 1);
51         median = sorted[n/2];
52 
53         // Normalize samples to [min, max] in as many quanta as we have distinct bars to print.
54         for (int i = 0; want_plot && i < n; i++) {
55             if (min == max) {
56                 // All samples are the same value.  Don't divide by zero.
57                 plot.append(kBars[0]);
58                 continue;
59             }
60 
61             double s = samples[i];
62             s -= min;
63             s /= (max - min);
64             s *= (SK_ARRAY_COUNT(kBars) - 1);
65             const size_t bar = (size_t)(s + 0.5);
66             SkASSERT_RELEASE(bar < SK_ARRAY_COUNT(kBars));
67             plot.append(kBars[bar]);
68         }
69     }
70 
71     double min;
72     double max;
73     double mean;    // Estimate of population mean.
74     double var;     // Estimate of population variance.
75     double median;
76     SkString plot;  // A single-line bar chart (_not_ histogram) of the samples.
77 };
78 
79 #endif//Stats_DEFINED
80