average.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. #include <linux/log2.h>
  11. /**
  12. * DOC: Exponentially Weighted Moving Average (EWMA)
  13. *
  14. * These are generic functions for calculating Exponentially Weighted Moving
  15. * Averages (EWMA). We keep a structure with the EWMA parameters and a scaled
  16. * up internal representation of the average value to prevent rounding errors.
  17. * The factor for scaling up and the exponential weight (or decay rate) have to
  18. * be specified thru the init fuction. The structure should not be accessed
  19. * directly but only thru the helper functions.
  20. */
  21. /**
  22. * ewma_init() - Initialize EWMA parameters
  23. * @avg: Average structure
  24. * @factor: Factor to use for the scaled up internal value. The maximum value
  25. * of averages can be ULONG_MAX/(factor*weight). For performance reasons
  26. * factor has to be a power of 2.
  27. * @weight: Exponential weight, or decay rate. This defines how fast the
  28. * influence of older values decreases. For performance reasons weight has
  29. * to be a power of 2.
  30. *
  31. * Initialize the EWMA parameters for a given struct ewma @avg.
  32. */
  33. void ewma_init(struct ewma *avg, unsigned long factor, unsigned long weight)
  34. {
  35. WARN_ON(!is_power_of_2(weight) || !is_power_of_2(factor));
  36. avg->weight = ilog2(weight);
  37. avg->factor = ilog2(factor);
  38. avg->internal = 0;
  39. }
  40. EXPORT_SYMBOL(ewma_init);
  41. /**
  42. * ewma_add() - Exponentially weighted moving average (EWMA)
  43. * @avg: Average structure
  44. * @val: Current value
  45. *
  46. * Add a sample to the average.
  47. */
  48. struct ewma *ewma_add(struct ewma *avg, unsigned long val)
  49. {
  50. avg->internal = avg->internal ?
  51. (((avg->internal << avg->weight) - avg->internal) +
  52. (val << avg->factor)) >> avg->weight :
  53. (val << avg->factor);
  54. return avg;
  55. }
  56. EXPORT_SYMBOL(ewma_add);