Stats.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #ifndef Stats_DEFINED
  8. #define Stats_DEFINED
  9. #include "include/core/SkString.h"
  10. #include "include/private/SkFloatingPoint.h"
  11. #include "src/core/SkTSort.h"
  12. #ifdef SK_BUILD_FOR_WIN
  13. static const char* kBars[] = { ".", "o", "O" };
  14. #else
  15. static const char* kBars[] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
  16. #endif
  17. struct Stats {
  18. Stats(const SkTArray<double>& samples, bool want_plot) {
  19. int n = samples.count();
  20. if (!n) {
  21. min = max = mean = var = median = 0;
  22. return;
  23. }
  24. min = samples[0];
  25. max = samples[0];
  26. for (int i = 0; i < n; i++) {
  27. if (samples[i] < min) { min = samples[i]; }
  28. if (samples[i] > max) { max = samples[i]; }
  29. }
  30. double sum = 0.0;
  31. for (int i = 0 ; i < n; i++) {
  32. sum += samples[i];
  33. }
  34. mean = sum / n;
  35. double err = 0.0;
  36. for (int i = 0 ; i < n; i++) {
  37. err += (samples[i] - mean) * (samples[i] - mean);
  38. }
  39. var = sk_ieee_double_divide(err, n-1);
  40. SkAutoTMalloc<double> sorted(n);
  41. memcpy(sorted.get(), samples.begin(), n * sizeof(double));
  42. SkTQSort(sorted.get(), sorted.get() + n - 1);
  43. median = sorted[n/2];
  44. // Normalize samples to [min, max] in as many quanta as we have distinct bars to print.
  45. for (int i = 0; want_plot && i < n; i++) {
  46. if (min == max) {
  47. // All samples are the same value. Don't divide by zero.
  48. plot.append(kBars[0]);
  49. continue;
  50. }
  51. double s = samples[i];
  52. s -= min;
  53. s /= (max - min);
  54. s *= (SK_ARRAY_COUNT(kBars) - 1);
  55. const size_t bar = (size_t)(s + 0.5);
  56. SkASSERT_RELEASE(bar < SK_ARRAY_COUNT(kBars));
  57. plot.append(kBars[bar]);
  58. }
  59. }
  60. double min;
  61. double max;
  62. double mean; // Estimate of population mean.
  63. double var; // Estimate of population variance.
  64. double median;
  65. SkString plot; // A single-line bar chart (_not_ histogram) of the samples.
  66. };
  67. #endif//Stats_DEFINED