python 中的更快除法
Faster division in python
我有这个 lambda 函数:
transfer = lambda x: 1.0 / (1.0 + np.e ** (-2.0*x))
此函数调用频率很高(超过 80 000 次)。 (我认为表达式除法 1 无效,但找不到好的替代方法。)我可以让它更快吗?
重写你的代码,这样你就可以先收集一个 numpy 数组中的所有 x 值,然后直接对你的 numpy 数组使用一个操作
import time
import numpy as np
data = np.random.random(size=100000)
result = list()
transfer = lambda x: 1.0 / (1.0 + np.e ** (-2.0 * x))
t1 = time.perf_counter()
for value in data:
y = transfer(value)
result.append(y)
result = np.array(result)
t2 = time.perf_counter()
print(f"time lambda = {t2 - t1} with sum {result.sum()}")
t3 = time.perf_counter()
# this line is the numpy expression of your transfer function
results2 = 1 / (1 + np.e ** (-2 * data))
t4 = time.perf_counter()
print(f"time numpy = {t4 - t3} with sum {results2.sum()}")
这段代码的输出是:
time lambda = 0.09890314500080422 with sum 71682.58495450807
time numpy = 0.0029907969874329865 with sum 71682.58495450807
所以 numpy 方法大约快 35 倍
我有这个 lambda 函数:
transfer = lambda x: 1.0 / (1.0 + np.e ** (-2.0*x))
此函数调用频率很高(超过 80 000 次)。 (我认为表达式除法 1 无效,但找不到好的替代方法。)我可以让它更快吗?
重写你的代码,这样你就可以先收集一个 numpy 数组中的所有 x 值,然后直接对你的 numpy 数组使用一个操作
import time
import numpy as np
data = np.random.random(size=100000)
result = list()
transfer = lambda x: 1.0 / (1.0 + np.e ** (-2.0 * x))
t1 = time.perf_counter()
for value in data:
y = transfer(value)
result.append(y)
result = np.array(result)
t2 = time.perf_counter()
print(f"time lambda = {t2 - t1} with sum {result.sum()}")
t3 = time.perf_counter()
# this line is the numpy expression of your transfer function
results2 = 1 / (1 + np.e ** (-2 * data))
t4 = time.perf_counter()
print(f"time numpy = {t4 - t3} with sum {results2.sum()}")
这段代码的输出是:
time lambda = 0.09890314500080422 with sum 71682.58495450807
time numpy = 0.0029907969874329865 with sum 71682.58495450807
所以 numpy 方法大约快 35 倍