Почему math.factorial намного медленнее в Python 2.x, чем 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
>>>
Я думал, что это может иметь какое-то отношение к преобразованию int/long, но factorial(10000L)
не быстрее в 2.7.
Ответы
Ответ 1
В 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 }
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 для обсуждения. Спасибо DSM за указание на это.