tvalentyn commented on a change in pull request #11092: [BEAM-9085] Fix
performance regression in SyntheticSource
URL: https://github.com/apache/beam/pull/11092#discussion_r405921080
##########
File path: sdks/python/apache_beam/testing/synthetic_pipeline.py
##########
@@ -61,6 +65,35 @@
np = None
+class _Random(Random):
+ """A subclass of `random.Random` from the Python Standard Library that
+ provides a method returning random bytes of arbitrary length.
+ """
+
+ # `numpy.random.RandomState` does not provide `random()` method, we keep this
+ # for compatibility reasons.
+ random_sample = Random.random
+
+ def bytes(self, length):
+ """Returns random bytes.
+
+ Args:
+ length (int): Number of random bytes.
+ """
+ n = length // 8 + 1
+ # pylint: disable=map-builtin-not-iterating
+ return struct.pack(
+ '{}Q'.format(n),
+ *map(self.getrandbits, itertools.repeat(64, n)))[:length]
Review comment:
Since we don't need py2 compatibility anymore, consider using `to_bytes`.
Here's an equivalent for chunk_size=8. It seems to be somewhat slower than
current method (perhaps since I'm not using `map+repeat()`), but with larger
`chuck_size`, seems to be more efficient. Large chunk size may be less
efficient for short bytesequences.
```
chunk_size_bytes = 8 // TBD - larger chunks seem to improve performance.
chunk_size_bits = chunk_size_bytes * 8
num_chunks = length // chunk_size_bytes + 1
return
b''.join([self.getrandbits(chunk_size_bits).to_bytes(chunk_size_bytes,
sys.byteorder) for _ in range(num_chunks)])[:length]
```
If you decide to keep current implementation - please add a comment
explaining the mechanics for readers not familiar with this code (we generate
8-byte stings, and then fit them into a representation of C++'s long-long,
which also takes up 8 bytes).
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services