我对以下代码的计时非常奇怪:
import numpy as np
s = 0
for i in range(10000000):
s += np.float64(1) # replace with np.float32 and built-in float
- 内置浮子:4.9秒
- float64: 10.5 秒
- float32: 45.0 秒
Why is float64
比慢两倍float
?为什么是float32
比float64慢5倍?
有什么办法可以避免使用惩罚np.float64
,并且有numpy
函数返回内置float
代替float64
?
我发现使用numpy.float64
比 Python 的 float 慢得多,并且numpy.float32
甚至更慢(即使我在 32 位机器上)。
numpy.float32
在我的 32 位机器上。因此,每次我使用各种 numpy 函数,例如numpy.random.uniform
,我将结果转换为float32
(以便进一步的操作将以 32 位精度执行)。
有没有办法在程序或命令行中的某个位置设置单个变量,并使所有 numpy 函数返回float32
代替float64
?
EDIT #1:
numpy.float64 是10 times在算术计算中比 float 慢。糟糕的是,即使在计算之前转换为浮点型再转换回来,程序的运行速度也会快 3 倍。为什么?我能做些什么来解决它吗?
我想强调的是,我的时间安排不是由于以下任何原因造成的:
- 该函数调用
- numpy 和 python float 之间的转换
- 对象的创建
我更新了我的代码以更清楚问题所在。使用新代码,我似乎看到使用 numpy 数据类型的性能提高了十倍:
from datetime import datetime
import numpy as np
START_TIME = datetime.now()
# one of the following lines is uncommented before execution
#s = np.float64(1)
#s = np.float32(1)
#s = 1.0
for i in range(10000000):
s = (s + 8) * s % 2399232
print(s)
print('Runtime:', datetime.now() - START_TIME)
时间安排是:
- float64: 34.56s
- float32: 35.11s
- 浮动:3.53s
只是为了它,我也尝试过:
从日期时间导入日期时间
将 numpy 导入为 np
START_TIME = datetime.now()
s = np.float64(1)
for i in range(10000000):
s = float(s)
s = (s + 8) * s % 2399232
s = np.float64(s)
print(s)
print('Runtime:', datetime.now() - START_TIME)
执行时间为13.28秒;实际上转换速度快了 3 倍float64
to float
然后返回而不是按原样使用它。尽管如此,转换还是要付出代价的,所以总的来说,与纯 python 相比,它慢了 3 倍多float
.
我的机器是:
- 英特尔酷睿 2 双核 T9300 (2.5GHz)
- WinXP 专业版(32 位)
- ActiveState Python 3.1.3.5
- numpy 1.5.1
EDIT #2:
感谢您的回答,他们帮助我了解如何处理这个问题。
但我仍然想知道下面的代码运行速度慢 10 倍的确切原因(也许基于源代码)float64
比与float
.
EDIT #3:
我在 Windows 7 x64 (Intel Core i7 930 @ 3.8GHz) 下重新运行代码。
同样,代码是:
from datetime import datetime
import numpy as np
START_TIME = datetime.now()
# one of the following lines is uncommented before execution
#s = np.float64(1)
#s = np.float32(1)
#s = 1.0
for i in range(10000000):
s = (s + 8) * s % 2399232
print(s)
print('Runtime:', datetime.now() - START_TIME)
时间安排是:
- 浮点64:16.1秒
- 浮动32:16.1秒
- 浮球:3.2秒
现在两者np
浮点数(64 或 32)比内置浮点数慢 5 倍float
。尽管如此,还是存在显着差异。我正试图弄清楚它从哪里来。
编辑结束