| 357 | |
| 358 | |
| 359 | class BandwidthRateTracker: |
| 360 | def __init__(self, alpha=0.8): |
| 361 | """Tracks the rate of bandwidth consumption |
| 362 | |
| 363 | :type a: float |
| 364 | :param a: The constant to use in calculating the exponentional moving |
| 365 | average of the bandwidth rate. Specifically it is used in the |
| 366 | following calculation: |
| 367 | |
| 368 | current_rate = alpha * new_rate + (1 - alpha) * current_rate |
| 369 | |
| 370 | This value of this constant should be between 0 and 1. |
| 371 | """ |
| 372 | self._alpha = alpha |
| 373 | self._last_time = None |
| 374 | self._current_rate = None |
| 375 | |
| 376 | @property |
| 377 | def current_rate(self): |
| 378 | """The current transfer rate |
| 379 | |
| 380 | :rtype: float |
| 381 | :returns: The current tracked transfer rate |
| 382 | """ |
| 383 | if self._last_time is None: |
| 384 | return 0.0 |
| 385 | return self._current_rate |
| 386 | |
| 387 | def get_projected_rate(self, amt, time_at_consumption): |
| 388 | """Get the projected rate using a provided amount and time |
| 389 | |
| 390 | :type amt: int |
| 391 | :param amt: The proposed amount to consume |
| 392 | |
| 393 | :type time_at_consumption: float |
| 394 | :param time_at_consumption: The proposed time to consume at |
| 395 | |
| 396 | :rtype: float |
| 397 | :returns: The consumption rate if that amt and time were consumed |
| 398 | """ |
| 399 | if self._last_time is None: |
| 400 | return 0.0 |
| 401 | return self._calculate_exponential_moving_average_rate( |
| 402 | amt, time_at_consumption |
| 403 | ) |
| 404 | |
| 405 | def record_consumption_rate(self, amt, time_at_consumption): |
| 406 | """Record the consumption rate based off amount and time point |
| 407 | |
| 408 | :type amt: int |
| 409 | :param amt: The amount that got consumed |
| 410 | |
| 411 | :type time_at_consumption: float |
| 412 | :param time_at_consumption: The time at which the amount was consumed |
| 413 | """ |
| 414 | if self._last_time is None: |
| 415 | self._last_time = time_at_consumption |
| 416 | self._current_rate = 0.0 |