Python提供了一种名为“long”的“bignum”类型,可以表示任意大的数字。这种类型的内部表示是什么?
我之所以问这个问题,部分原因是我想知道在这些数字上哪些操作可能特别快或特别慢。例如,相比乘法或除法,位移是否特别快速(就像“常规”整数一样)?
我之所以问这个问题,部分原因是我想知道在这些数字上哪些操作可能特别快或特别慢。例如,相比乘法或除法,位移是否特别快速(就像“常规”整数一样)?
好的,这是我写的。我不确定这有多好,但你可以把它作为更精细和完整基准测试的起点。
import timeit
def timef(f, *args):
return timeit.timeit(lambda: f(*args), number = 1000000) # repetitions
tests = {
'addition' : lambda x: x + 17,
'substraction' : lambda x: x - 17,
'multiplication': lambda x: x * 17,
'division' : lambda x: x / 17,
'float division': lambda x: x / 17.0
}
for name, f in tests.items():
print 'int {0}'.format(name).ljust(20), timef(f, 0)
print 'long {0}'.format(name).ljust(20), timef(f, 10 ** 50)
print
int()
操作确实更快,但并不是非常快。
int
和long
,但在Python3中,只有long
(重命名为int
)。这是Python2int
的实现方式。 - Two-Bit Alchemistint
。 - user395760longintrepr.h
。 - jfs