average.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * lib/average.c
  3. *
  4. * This source code is licensed under the GNU General Public License,
  5. * Version 2. See the file COPYING for more details.
  6. */
  7. #include <linux/module.h>
  8. #include <linux/average.h>
  9. #include <linux/bug.h>
  10. /**
  11. * DOC: Exponentially Weighted Moving Average (EWMA)
  12. *
  13. * These are generic functions for calculating Exponentially Weighted Moving
  14. * Averages (EWMA). We keep a structure with the EWMA parameters and a scaled
  15. * up internal representation of the average value to prevent rounding errors.
  16. * The factor for scaling up and the exponential weight (or decay rate) have to
  17. * be specified thru the init fuction. The structure should not be accessed
  18. * directly but only thru the helper functions.
  19. */
  20. /**
  21. * ewma_init() - Initialize EWMA parameters
  22. * @avg: Average structure
  23. * @factor: Factor to use for the scaled up internal value. The maximum value
  24. * of averages can be ULONG_MAX/(factor*weight).
  25. * @weight: Exponential weight, or decay rate. This defines how fast the
  26. * influence of older values decreases. Has to be bigger than 1.
  27. *
  28. * Initialize the EWMA parameters for a given struct ewma @avg.
  29. */
  30. void ewma_init(struct ewma *avg, unsigned long factor, unsigned long weight)
  31. {
  32. WARN_ON(weight <= 1 || factor == 0);
  33. avg->internal = 0;
  34. avg->weight = weight;
  35. avg->factor = factor;
  36. }
  37. EXPORT_SYMBOL(ewma_init);
  38. /**
  39. * ewma_add() - Exponentially weighted moving average (EWMA)
  40. * @avg: Average structure
  41. * @val: Current value
  42. *
  43. * Add a sample to the average.
  44. */
  45. struct ewma *ewma_add(struct ewma *avg, unsigned long val)
  46. {
  47. avg->internal = avg->internal ?
  48. (((avg->internal * (avg->weight - 1)) +
  49. (val * avg->factor)) / avg->weight) :
  50. (val * avg->factor);
  51. return avg;
  52. }
  53. EXPORT_SYMBOL(ewma_add);