Xiao Guangrong | 0007ece | 2012-09-17 16:31:14 +0800 | [diff] [blame] | 1 | #include <math.h> |
| 2 | |
| 3 | #include "stat.h" |
| 4 | |
| 5 | void update_stats(struct stats *stats, u64 val) |
| 6 | { |
| 7 | double delta; |
| 8 | |
| 9 | stats->n++; |
| 10 | delta = val - stats->mean; |
| 11 | stats->mean += delta / stats->n; |
| 12 | stats->M2 += delta*(val - stats->mean); |
David Ahern | ffe4f3c | 2013-08-02 14:05:40 -0600 | [diff] [blame] | 13 | |
| 14 | if (val > stats->max) |
| 15 | stats->max = val; |
| 16 | |
| 17 | if (val < stats->min) |
| 18 | stats->min = val; |
Xiao Guangrong | 0007ece | 2012-09-17 16:31:14 +0800 | [diff] [blame] | 19 | } |
| 20 | |
| 21 | double avg_stats(struct stats *stats) |
| 22 | { |
| 23 | return stats->mean; |
| 24 | } |
| 25 | |
| 26 | /* |
| 27 | * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance |
| 28 | * |
| 29 | * (\Sum n_i^2) - ((\Sum n_i)^2)/n |
| 30 | * s^2 = ------------------------------- |
| 31 | * n - 1 |
| 32 | * |
| 33 | * http://en.wikipedia.org/wiki/Stddev |
| 34 | * |
| 35 | * The std dev of the mean is related to the std dev by: |
| 36 | * |
| 37 | * s |
| 38 | * s_mean = ------- |
| 39 | * sqrt(n) |
| 40 | * |
| 41 | */ |
| 42 | double stddev_stats(struct stats *stats) |
| 43 | { |
| 44 | double variance, variance_mean; |
| 45 | |
David Ahern | 45528f7 | 2013-05-25 18:24:48 -0600 | [diff] [blame] | 46 | if (stats->n < 2) |
Xiao Guangrong | 0007ece | 2012-09-17 16:31:14 +0800 | [diff] [blame] | 47 | return 0.0; |
| 48 | |
| 49 | variance = stats->M2 / (stats->n - 1); |
| 50 | variance_mean = variance / stats->n; |
| 51 | |
| 52 | return sqrt(variance_mean); |
| 53 | } |
| 54 | |
| 55 | double rel_stddev_stats(double stddev, double avg) |
| 56 | { |
| 57 | double pct = 0.0; |
| 58 | |
| 59 | if (avg) |
| 60 | pct = 100.0 * stddev/avg; |
| 61 | |
| 62 | return pct; |
| 63 | } |