1
0

Average.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. struct Average
  16. {
  17. uint64_t shiftedAvg;
  18. int shiftCount;
  19. int weight;
  20. };
  21. static inline void Average_init(struct Average* average, uint64_t factor, uint64_t weight)
  22. {
  23. average->weight = Bits_log2x64(weight);
  24. average->shiftCount = Bits_log2x64(factor);
  25. average->shiftedAvg = 0;
  26. // must be a power of 2
  27. Assert_true((1 << average->shiftCount) == factor);
  28. Assert_true((1 << average->weight) == weight);
  29. }
  30. static inline void Average_accumulate(struct Average* average, uint64_t value)
  31. {
  32. if (!average->shiftedAvg) {
  33. average->shiftedAvg = value << average->shiftCount;
  34. return;
  35. }
  36. uint64_t sha = average->shiftedAvg;
  37. sha = ( (sha << average->weight) - sha + (value << avg->shiftCount) ) >> average->weight;
  38. average->shiftedAvg = sha;
  39. }
  40. static inline uint64_t Average_value(struct Average* average)
  41. {
  42. return avg->shiftedAvg >> avg->shiftCount;
  43. }