rateLimiter.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python3
  2. # ################################################################
  3. # Copyright (c) 2018-2021, Facebook, Inc.
  4. # All rights reserved.
  5. #
  6. # This source code is licensed under both the BSD-style license (found in the
  7. # LICENSE file in the root directory of this source tree) and the GPLv2 (found
  8. # in the COPYING file in the root directory of this source tree).
  9. # You may select, at your option, one of the above-listed licenses.
  10. # ##########################################################################
  11. # Rate limiter, replacement for pv
  12. # this rate limiter does not "catch up" after a blocking period
  13. # Limitations:
  14. # - only accepts limit speed in MB/s
  15. import sys
  16. import time
  17. MB = 1024 * 1024
  18. rate = float(sys.argv[1]) * MB
  19. start = time.time()
  20. total_read = 0
  21. # sys.stderr.close() # remove error message, for Ctrl+C
  22. try:
  23. buf = " "
  24. while len(buf):
  25. now = time.time()
  26. to_read = max(int(rate * (now - start)), 1)
  27. max_buf_size = 1 * MB
  28. to_read = min(to_read, max_buf_size)
  29. start = now
  30. buf = sys.stdin.buffer.read(to_read)
  31. sys.stdout.buffer.write(buf)
  32. except (KeyboardInterrupt, BrokenPipeError) as e:
  33. pass