【问题标题】:Does Python have a library that produces data as fast os.urandom but is reproducible?Python 是否有一个库可以像 os.urandom 一样快速生成数据但可重现?
【发布时间】:2018-09-11 23:33:33
【问题描述】:

有没有 Python 库可以像 os.urandom 一样快速生成随机数据,但如果给定种子,数据可以重现?

【问题讨论】:

  • 您在“Python 随机种子”上的搜索结果如何没有出现?
  • 你知道os.urandom 和伪随机生成器之间的区别,对吧?
  • pv < /dev/urandom > /dev/null 给出的速度因系统而异。我的集群大约为 ~13MiB/s,其中一个产生 ~180MiB/s。这些并不是特别快的速度。你打算用这些随机数据做什么?
  • 我知道 os.urandom 是完全随机的,但我找不到合适的伪随机生成器来做类似的事情。我正在使用这些数据来测试对一堆 lun 的写入功能。

标签: python python-3.x random-data


【解决方案1】:

您可以使用random.seed 生成可重现的序列。唯一的问题是让 Python 快速生成随机字节。您可以使用a trick observed by @jfs with random.getrandbits 来减少 Python 必须执行的处理量:

import random

def almost_urandom(n):
    return random.getrandbits(8 * n).to_bytes(n, 'big')

random.seed 让您确定性地生成字节:

In [26]: random.seed(0)

In [27]: almost_urandom(10)
Out[27]: b'\xc2\tb\x9fo\xbe\xd8,\x07\xcd'

In [28]: almost_urandom(10)
Out[28]: b'\n]k\xaa\x94U\xe3\xe7\x06\x82'

In [29]: random.seed(0)

In [30]: almost_urandom(10)
Out[30]: b'\xc2\tb\x9fo\xbe\xd8,\x07\xcd'

In [31]: almost_urandom(10)
Out[31]: b'\n]k\xaa\x94U\xe3\xe7\x06\x82'

对我来说,它的运行速度比 os.urandom() 快一个数量级,即使对于数百万的 n 也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 2019-03-13
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2019-11-28
    • 2015-08-15
    • 2022-12-04
    相关资源
    最近更新 更多