Performance of choice vs randint

前端 未结 1 1907
别跟我提以往
别跟我提以往 2021-01-04 13:16

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

相关标签:
1条回答
  • 2021-01-04 13:30

    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))]
    
    0 讨论(0)
提交回复
热议问题