Is divmod() faster than using the % and // operators?

后端 未结 2 1537
天命终不由人
天命终不由人 2020-12-25 11:20

I remember from assembly that integer division instructions yield both the quotient and remainder. So, in python will the built-in divmod() function be better performance-wi

2条回答
  •  醉话见心
    2020-12-25 11:54

    Martijn's answer is correct if you're using "small" native integers, where arithmetic operations are very fast compared to function calls. However, with bigints, it's a whole different story:

    >>> import timeit
    >>> timeit.timeit('divmod(n, d)', 'n, d = 2**74207281 - 1, 26', number=1000)
    24.22666597366333
    >>> timeit.timeit('n // d, n % d', 'n, d = 2**74207281 - 1, 26', number=1000)
    49.517399072647095
    

    when dividing a 22-million-digit number, divmod is almost exactly twice as fast as doing the division and modulus separately, as you might expect.

    On my machine, the crossover occurs somewhere around 2^63, but don't take my word for it. As Martijn says, measure! When performance really matters, don't assume that what held true in one place will still be true in another.

提交回复
热议问题