[Tutor] Why is random.choice so much slower than random.random()?
rabidpoobear at gmail.com
Thu Oct 12 11:24:55 CEST 2006
Dick Moores wrote:
> Why is random.choice so much slower than random.random()? In fact, by
> a factor of 12! And randint(). Some 25 times slower than random(). Why?
> (I know that random() is the basis for most of the other functions in
> the random module, and a look at random.py, though I don't complete
> understand it, gives me an idea what's going on with randint(), etc., still...)
I haven't looked at the random code, but what I expect is happening is that
you need to
1) get a random number
2) convert that random number into an index into your list. eg. [0,1]
any random number < .5 would be index 0.
recall that random goes from 0 to 1.
3) grab that item from the list and return it.
I'm guessing that step 2 and step 3 are why it takes a while, since
these are probably implemented in Python.
It might do
so there's the overhead of generating the range.
Course this is completely speculation and may be not true at all, but I
thought I'd give it a shot :)
More information about the Tutor