Tim Peters <t...@python.org> added the comment:

Closing this now because the pull request did, I believe, all that can be done 
at the function level. Exponents of 1 and 2 are well within a factor of 2 of 
repeated multiplication now, and it's essentially a tie at exponent 3 now. 
Above that, pow() wins now. On my box.

Doing better would require a smarter compiler, which, e.g., knew that `pow(x, 
2)` is the same as `x*x`. But, as is, `pow` is just another identifier to 
CPython's compiler, and may refer to any code at all. `i**2` isn't really much 
better, because CPython just redirects to type(i)'s __pow__ function at 
runtime. Which, again to the compiler, may refer to any code at all.

`pow()` is quite an involved function, needing to cater to all sorts of things, 
including possible reduction by the optional modulus, and possibly negative 
exponents.

`pow(i, 2)` (same as `i**2` under the covers) does exactly one Python-int 
multiplication now, same as `i*i`. That's fast. In either case overheads 
account for the bulk of the elapsed time. The overhead of going around the eval 
loop an "extra" time (in `i*i`) and doing another name lookup is simply smaller 
than all the overheads `pow()` incurs to _deduce_, at runtime, that it's only 
being asked to do one multiply.

----------
resolution:  -> fixed
stage: patch review -> resolved
status: open -> closed

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44376>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to