average.c 1.9 KB

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