Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #61177
| From | Neil Cerutti <neilc@norwich.edu> |
|---|---|
| Subject | Re: Does Python optimize low-power functions? |
| Date | 2013-12-06 19:01 +0000 |
| Organization | Norwich University |
| References | <5ea86e1b-f5b5-49d1-acfb-22ee4d9a1f16@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3660.1386356539.18130.python-list@python.org> (permalink) |
On 2013-12-06, John Ladasky <john_ladasky@sbcglobal.net> wrote:
> The following two functions return the same result:
>
> x**2
> x*x
>
> But they may be computed in different ways. The first choice
> can accommodate non-integer powers and so it would logically
> proceed by taking a logarithm, multiplying by the power (in
> this case, 2), and then taking the anti-logarithm. But for a
> trivial value for the power like 2, this is clearly a wasteful
> choice. Just multiply x by itself, and skip the expensive log
> and anti-log steps.
>
> My question is, what do Python interpreters do with power
> operators where the power is a small constant, like 2? Do they
> know to take the shortcut?
It uses a couple of fast algorithms for computing powers. Here's
the excerpt with the comments identifying the algorithms used.
>From longobject.c:
2873 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
2874 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2875 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
...
2886 else {
2887 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
The only outright optimization of the style I think your
describing that I can see is it quickly returns zero when modulus
is one.
I'm not a skilled or experienced CPython source reader, though.
--
Neil Cerutti
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Does Python optimize low-power functions? John Ladasky <john_ladasky@sbcglobal.net> - 2013-12-06 10:16 -0800
Re: Does Python optimize low-power functions? Neil Cerutti <neilc@norwich.edu> - 2013-12-06 19:01 +0000
Re: Does Python optimize low-power functions? Robert Kern <robert.kern@gmail.com> - 2013-12-06 19:12 +0000
RE: Does Python optimize low-power functions? Nick Cash <nick.cash@npcinternational.com> - 2013-12-06 19:32 +0000
Re: Does Python optimize low-power functions? John Ladasky <john_ladasky@sbcglobal.net> - 2013-12-06 11:43 -0800
Re: Does Python optimize low-power functions? Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-12-06 20:57 +0000
Re: Does Python optimize low-power functions? Michael Torrie <torriem@gmail.com> - 2013-12-07 19:00 -0700
csiph-web