blob: 3e65081e05925d3b34cbffdcb80ffa7e2e237289 [file] [log] [blame]
Yann Colleta996b1f2018-08-10 17:39:00 -07001#!/usr/bin/env python3
Yann Collet681a3822018-08-10 12:25:52 -07002
3# ################################################################
Elliott Hughes44aba642023-09-12 20:18:59 +00004# Copyright (c) Meta Platforms, Inc. and affiliates.
Yann Collet681a3822018-08-10 12:25:52 -07005# 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 Terrellac58c8d2020-03-26 15:19:05 -070010# You may select, at your option, one of the above-listed licenses.
Yann Collet681a3822018-08-10 12:25:52 -070011# ##########################################################################
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
18import sys
19import time
20
Yann Colleta996b1f2018-08-10 17:39:00 -070021MB = 1024 * 1024
22rate = float(sys.argv[1]) * MB
Yann Collet681a3822018-08-10 12:25:52 -070023start = time.time()
24total_read = 0
25
Yann Collet09c9cf32018-08-13 12:13:47 -070026# sys.stderr.close() # remove error message, for Ctrl+C
Yann Colletf3aa5102018-08-13 11:38:55 -070027
Yann Collete11f91b2018-08-13 11:48:25 -070028try:
29 buf = " "
30 while len(buf):
31 now = time.time()
Yann Collet09c9cf32018-08-13 12:13:47 -070032 to_read = max(int(rate * (now - start)), 1)
Yann Collete11f91b2018-08-13 11:48:25 -070033 max_buf_size = 1 * MB
34 to_read = min(to_read, max_buf_size)
Yann Collet09c9cf32018-08-13 12:13:47 -070035 start = now
Yann Colletf3aa5102018-08-13 11:38:55 -070036
Yann Collete11f91b2018-08-13 11:48:25 -070037 buf = sys.stdin.buffer.read(to_read)
Yann Collete11f91b2018-08-13 11:48:25 -070038 sys.stdout.buffer.write(buf)
Yann Collete11f91b2018-08-13 11:48:25 -070039
40except (KeyboardInterrupt, BrokenPipeError) as e:
41 pass