为什么Python 2.x中的math.factorial比3.x慢得多?

Kar*_*tel 32 python performance python-2.x factorial python-3.x

我在我的机器上得到以下结果:

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100)
1.9785256226699202
>>>

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100)
9.403801111593792
>>>
Run Code Online (Sandbox Code Playgroud)

我认为这可能与int/long转换有关,但factorial(10000L)在2.7中没有任何更快.

agf*_*agf 45

Python 2使用了朴素因子算法:

1121 for (i=1 ; i<=x ; i++) {
1122     iobj = (PyObject *)PyInt_FromLong(i);
1123     if (iobj == NULL)
1124         goto error;
1125     newresult = PyNumber_Multiply(result, iobj);
1126     Py_DECREF(iobj);
1127     if (newresult == NULL)
1128         goto error;
1129     Py_DECREF(result);
1130     result = newresult;
1131 }
Run Code Online (Sandbox Code Playgroud)

Python 3使用了分而治之的因子算法:

1229 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1230 * computed separately, and then combined using a left shift.

有关讨论,请参阅Python Bugtracker问题.感谢帝斯曼指出这一点.

  • 有趣的是,有点遗憾,尽管表面上是用 C 实现的,但 Python 2.x 中的 `math.factorial` 似乎并没有比在纯 Python 中使用简单的 `for` 循环快太多。使用 Python 长整数的开销似乎耗尽了在 C 中循环可以获得的任何收益。正如链接的 Python bugtracker 线程中所评论的那样,如果你真的想要这种事情的性能,请使用 `gmpy`。 (2认同)
  • @agf:我没有假设任何事情,也不是说 C 级 Python 对象性能很差。我什至不知道“同样未优化”的实现是什么,因为如果你想复制完整的功能,你必须实现 bignums。令我惊讶的是,Python 开发人员决定在“math”模块中包含一个仅比纯 Python 函数好一点的事实,该模块的目的是(并且在似乎所有其他方面都是)纯 C 例程的薄包装器(阶乘不是)。 (2认同)