gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:58:13 28 4
gpt4 key购买 nike

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

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
>>>

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

最佳答案

Python 2 使用 naive factorial algorithm :

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 }

Python 3 使用 divide-and-conquer factorial algorithm :

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

Python Bugtracker issue讨论。感谢帝斯曼指出这一点。

关于python - 为什么 Python 2.x 中的 math.factorial 比 3.x 慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815252/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com