为什么是数学.阶乘Python2.x比3.x慢得多?

2024-05-12 19:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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中没有更快。在


Tags: orimportdefaultlicenseontypebithelp
1条回答
网友
1楼 · 发布于 2024-05-12 19:21:33

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 }

Python3使用divide-and-conquer factorial algorithm

^{pr2}$

有关讨论,请参阅Python Bugtracker issue。感谢帝斯曼指出这一点。在

相关问题 更多 >