I want to pick a random integer between a
and b
, inclusive.
I know 3 ways of doing it. However, their performance seems very counter-intuit
It's just implementation details. randint delegates to randrange, so it has another layer of function call overhead, and randrange
goes through a lot of argument checking and other crud. In contrast, choice is a really simple one-liner.
Here's the code path randint
goes through for this call, with comments and unexecuted code stripped out:
def randint(self, a, b):
return self.randrange(a, b+1)
def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=1L<<BPF):
istart = _int(start)
if istart != start:
# not executed
if stop is None:
# not executed
istop = _int(stop)
if istop != stop:
# not executed
width = istop - istart
if step == 1 and width > 0:
if width >= _maxwidth:
# not executed
return _int(istart + _int(self.random()*width))
And here's the code path choice
goes through:
def choice(self, seq):
return seq[int(self.random() * len(seq))]