human_throughput.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from typing import Optional
  2. from .features import FEATURES, conv_space
  3. from .human_count import fn_human_count
  4. SPEC = (
  5. (24., "/d", 2),
  6. (60., "/h", 1),
  7. (60., "/m", 1),
  8. # "/s" in code.
  9. )
  10. def __human_throughput(val: float, unit: str, prec: Optional[int], space: str, fn_count) -> str:
  11. val *= 60. * 60. * 24.
  12. for size, scale, dec in SPEC:
  13. r = round(val, dec)
  14. if r >= size:
  15. val /= size
  16. continue
  17. if prec is not None:
  18. r = round(val, prec)
  19. elif r % 1. == 0.:
  20. prec = 0
  21. elif (r * 10.) % 1. == 0.:
  22. prec = 1
  23. else:
  24. prec = 2
  25. return '{:.{}f}{}{}{}'.format(r, prec, space, unit, scale)
  26. return '{}/s'.format(fn_count(val, unit, prec))
  27. def fn_human_throughput(space: bool, d1024: bool, iec: bool):
  28. def run(val: float, unit: str, prec: Optional[int]):
  29. return __human_throughput(val, unit, prec, space, fn_count)
  30. fn_count = fn_human_count(space, d1024, iec)
  31. space = conv_space(space)
  32. return run
  33. class HumanThroughput(object):
  34. def __init__(self, value, unit):
  35. assert value >= 0.
  36. self._value = value
  37. self._unit = unit
  38. @property
  39. def value(self):
  40. return self._value
  41. def unit(self, value: str) -> 'HumanThroughput':
  42. self._unit = value
  43. return self
  44. def as_human(self, prec: Optional[int] = None) -> str:
  45. """Return a beautiful representation of this count.
  46. It dynamically calculates the best scale to use.
  47. Args:
  48. prec: an optional custom precision
  49. Returns:
  50. the human friendly representation.
  51. """
  52. return fn_human_throughput(FEATURES.feature_space, FEATURES.feature_1024,
  53. FEATURES.feature_iec)(self._value, self._unit, prec)
  54. def __str__(self):
  55. return self.as_human()
  56. def __repr__(self): # pragma: no cover
  57. return 'HumanCount{{ value={} }} -> {}'.format(self._value, self)
  58. def __eq__(self, other):
  59. return self.__str__() == other