十进制Python与浮点运行时

Whi*_*hia 7 python floating-point decimal

关于在使用这两种不同数据类型之间我应该期待什么样的运行时差异的一般问题.

我的测试:

test = [100.0897463, 1.099999939393,1.37382829829393,29.1937462874847272,2.095478262874647474]
test2 = [decimal.Decimal('100.0897463'), decimal.Decimal('1.09999993939'), decimal.Decimal('1.37382829829'), decimal.Decimal('29.1937462875'), decimal.Decimal('2.09547826287')]

def average(numbers, ddof=0):
    return sum(numbers) / (len(numbers)-ddof)

%timeit average(test)
%timeit average(test2)
Run Code Online (Sandbox Code Playgroud)

运行时间的差异是:
1000000次循环,最佳3:364 ns每循环
10000次循环,最佳3:每循环80.3μs

所以使用十进制比使用浮点数慢大约200倍.在确定使用哪种数据类型时,这种差异是否正常并且与我期望的一致?

cas*_*evh 10

根据您看到的时差,您可能正在使用Python 2.x. 在Python 2.x中,decimal模块是用Python编写的,而且速度很慢.从Python 3.2开始,decimal模块被重写为C并且速度更快.

在我的系统上使用Python 2.7,decimal模块慢了大约180倍.使用Python 3.5,该decimal模块的速度只有2.5倍.

如果你关心decimal性能,Python 3要快得多.


Jea*_*bre 5

你得到更好的速度float,因为Python的float使用硬件浮点寄存器可用时(这可以用现代计算机),而Decimal采用全标量/软件实现。

但是,Decimal当您遇到float类型的经典浮点精度问题时,您可以更好地控制。查看经典的 StackOverflow Q&A浮点数学被破坏了吗?例如。