Python:随机系统时间种子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27276135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:36:27  来源:igfitidea点击:

Python: Random System time seed

pythonrandomtime

提问by Academiphile

In python, and assuming I'm on a system which has a random seed generator, how do I get random.seed() to use system time instead? (As if /dev/urandom did not exist)

在 python 中,假设我在一个有随机种子生成器的系统上,我如何让 random.seed() 改为使用系统时间?(好像 /dev/urandom 不存在一样)

采纳答案by Quint

import random
from datetime import datetime
random.seed(datetime.now())

回答by Elisha

you can do

你可以做

import random
import time
random.seed(time.time())

回答by Schmouk

Do you know this library: PyRandLib? See:

你知道这个库:PyRandLib吗?看:

https://schmouk.github.io/PyRandLib/ to easily download archives versions, and
https://github.com/schmouk/PyRandLib to get access to the code.

This library contains many of the best-in-class pseudo-random numbers generators while acting exactly as does the Python "built-in" library random (just un-zip or un-tar the downloaded archive in the 'Lib/site-packages/' sub-directory of your Python directory).

该库包含许多一流的伪随机数生成器,同时与 Python“内置”库 random 完全一样(只需解压缩或解压缩 'Lib/site-packages /' Python 目录的子目录)。

From the code, and from module 'fastrand32.py', you'll get a quite more sophisticated way to feed random with a shuffled version of current time. For your purpose, this would become:

从代码和模块“fastrand32.py”中,您将获得一种更复杂的方式来随机提供当前时间的混洗版本。为了您的目的,这将成为:

import time
import random

t = int( time.time() * 1000.0 )
random.seed( ((t & 0xff000000) >> 24) +
             ((t & 0x00ff0000) >>  8) +
             ((t & 0x0000ff00) <<  8) +
             ((t & 0x000000ff) << 24)   )

This provides a main advantage: for very short periods of time, the initial seeds for feeding the pseudo-random generator will be hugely different between two successive calls.

这提供了一个主要优势:在很短的时间内,用于提供伪随机生成器的初始种子将在两次连续调用之间存在巨大差异。