为什么Python 2.x中的math.factorial比3.x慢得多? [英] Why is math.factorial much slower in Python 2.x than 3.x?
本文介绍了为什么Python 2.x中的math.factorial比3.x慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在计算机上得到以下结果:
I get the following results on my machine:
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中并没有更快的速度.
I thought this might have something to do with int/long conversion, but factorial(10000L)
isn't any faster in 2.7.
推荐答案
Python 2使用天真阶乘算法:
Python 2 uses the 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使用分而治之阶乘算法:
Python 3 uses the divide-and-conquer factorial algorithm:
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指出这一点.
See the Python Bugtracker issue for the discussion. Thanks DSM for pointing that out.
这篇关于为什么Python 2.x中的math.factorial比3.x慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文