title: Why (in Python) is random.randint so much slower than random.random?
body: <p>I got curious about the relative speeds of some random integer generating code. I wrote the following to check it out:</p>
  <pre><code>from random import random
  from random import choice
  from random import randint
  from math import floor
  import time
  
  def main():
      times = 1000000
      
      startTime = time.time()
      for i in range(times):
          randint(0,9)
      print(time.time()-startTime)
      
      startTime = time.time()
      for i in range(times):
          choice([0,1,2,3,4,5,6,7,8,9])
      print(time.time()-startTime)
      
      startTime = time.time()
      for i in range(times):
          floor(10*random())##generates random integers in the same range as randint(0,9)
      print(time.time()-startTime)
  
  main()
  </code></pre>
  <p>The results of one trial of this code were</p>
  <blockquote>
  <p>0.9340872764587402</p>
  <p>0.6552846431732178</p>
  <p>0.23188304901123047</p>
  </blockquote>
  <p>Even after executing multiplication and math.floor, the final way of generating integers was by far fastest. Messing with the size of the range from which numbers were generated didn't change anything.</p>
  <p>So, why is random way faster than randint? and is there any reason why (besides ease of use, readability, and not inviting mistakes) that one would prefer randint to random (e.g., randint produces more random pseudo-random integers)? If <code>floor(x*random())</code> feels not readable enough but you want faster code, should you go for a specialized routine?</p>
  <pre><code>def myrandint(low,high):   ###still about 1.6 longer than the above, but almost 2.5 times faster than random.randint
      return floor((high-low+1)*random())+low  ##returns a random integer between low and high, inclusive. Results may not be what you expect if int(low) != low, etc. But the numpty who writes 'randint(1.9,3.2)' gets what they deserve.
    
  </code></pre>