Yann Collet | a996b1f | 2018-08-10 17:39:00 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Yann Collet | 681a382 | 2018-08-10 12:25:52 -0700 | [diff] [blame] | 2 | |
| 3 | # ################################################################ |
Elliott Hughes | 44aba64 | 2023-09-12 20:18:59 +0000 | [diff] [blame] | 4 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
Yann Collet | 681a382 | 2018-08-10 12:25:52 -0700 | [diff] [blame] | 5 | # All rights reserved. |
| 6 | # |
| 7 | # This source code is licensed under both the BSD-style license (found in the |
| 8 | # LICENSE file in the root directory of this source tree) and the GPLv2 (found |
| 9 | # in the COPYING file in the root directory of this source tree). |
Nick Terrell | ac58c8d | 2020-03-26 15:19:05 -0700 | [diff] [blame] | 10 | # You may select, at your option, one of the above-listed licenses. |
Yann Collet | 681a382 | 2018-08-10 12:25:52 -0700 | [diff] [blame] | 11 | # ########################################################################## |
| 12 | |
| 13 | # Rate limiter, replacement for pv |
| 14 | # this rate limiter does not "catch up" after a blocking period |
| 15 | # Limitations: |
| 16 | # - only accepts limit speed in MB/s |
| 17 | |
| 18 | import sys |
| 19 | import time |
| 20 | |
Yann Collet | a996b1f | 2018-08-10 17:39:00 -0700 | [diff] [blame] | 21 | MB = 1024 * 1024 |
| 22 | rate = float(sys.argv[1]) * MB |
Yann Collet | 681a382 | 2018-08-10 12:25:52 -0700 | [diff] [blame] | 23 | start = time.time() |
| 24 | total_read = 0 |
| 25 | |
Yann Collet | 09c9cf3 | 2018-08-13 12:13:47 -0700 | [diff] [blame] | 26 | # sys.stderr.close() # remove error message, for Ctrl+C |
Yann Collet | f3aa510 | 2018-08-13 11:38:55 -0700 | [diff] [blame] | 27 | |
Yann Collet | e11f91b | 2018-08-13 11:48:25 -0700 | [diff] [blame] | 28 | try: |
| 29 | buf = " " |
| 30 | while len(buf): |
| 31 | now = time.time() |
Yann Collet | 09c9cf3 | 2018-08-13 12:13:47 -0700 | [diff] [blame] | 32 | to_read = max(int(rate * (now - start)), 1) |
Yann Collet | e11f91b | 2018-08-13 11:48:25 -0700 | [diff] [blame] | 33 | max_buf_size = 1 * MB |
| 34 | to_read = min(to_read, max_buf_size) |
Yann Collet | 09c9cf3 | 2018-08-13 12:13:47 -0700 | [diff] [blame] | 35 | start = now |
Yann Collet | f3aa510 | 2018-08-13 11:38:55 -0700 | [diff] [blame] | 36 | |
Yann Collet | e11f91b | 2018-08-13 11:48:25 -0700 | [diff] [blame] | 37 | buf = sys.stdin.buffer.read(to_read) |
Yann Collet | e11f91b | 2018-08-13 11:48:25 -0700 | [diff] [blame] | 38 | sys.stdout.buffer.write(buf) |
Yann Collet | e11f91b | 2018-08-13 11:48:25 -0700 | [diff] [blame] | 39 | |
| 40 | except (KeyboardInterrupt, BrokenPipeError) as e: |
| 41 | pass |