Whats the difference between os.urandom() and random?

前端 未结 2 1317
面向向阳花
面向向阳花 2020-12-29 12:06

On the random module python page (Link Here) there is this warning:

Warning: The pseudo-random generators of this module should not b

2条回答
  •  旧巷少年郎
    2020-12-29 12:44

    So whats the difference between os.urandom() and random?

    Random itself is predicable. That means that given the same seed the sequence of numbers generated by random is the same. Take a look at this question for a better explanation. This question also illustrates than random isn't really random.

    This is generally the case for most programming languages - the generation of random numbers is not truly random. You can use these numbers when cryptographic security is not a concern or if you want the same pattern of numbers to be generated.

    Is one closer to a true random than the other?

    Not sure how to answer this question because truly random numbers cannot be generated. Take a look at this article or this question for more information.

    Since random generates a repeatable pattern I would say that os.urandom() is certainly more "random"

    Would the secure random be overkill in non-cryptographic instances?

    I wrote the following functions and there doesn't appear to be a huge time difference. However, if you don't need cryptographically secure numbers it doesn't really make sense to use os.urandom(). Again it comes down to the use case, do you want a repeatable pattern, how "random" do you want your numbers, etc?

    import time
    import os
    import random
    
    
    def generate_random_numbers(x): 
      start = time.time()
      random_numbers = []
      for _ in range(x):
        random_numbers.append(random.randrange(1,10,1))
      end = time.time()
      print(end - start)
    
    
    def generate_secure_randoms(x):
      start = time.time()
      random_numbers = []
      for _ in range(x):
        random_numbers.append(os.urandom(1))
      end = time.time()
      print(end - start)
    
    
    generate_random_numbers(10000)
    generate_secure_randoms(10000)
    

    Results:

    0.016040563583374023
    0.013456106185913086
    

    Are there any other random modules in python?

    Python 3.6 introduces the new secrets module

提交回复
热议问题