我有一个由np.uint64
组成的Numy数组,其中只包含0
或1
值,我必须将0
映射到np.float64(1.0)
,并将1
映射到np.float64(-1.0)
.
因为解释器不知道它只需要转换0
和1
,所以它使用了代价高昂的通用算法,所以我想使用一个带有结果的数组,并使用uint64
作为数组的索引,避免了任何转换,但它更慢.
import numpy as np
import timeit
random_bit = np.random.randint(0, 2, size=(10000), dtype=np.uint64)
def np_cast(random_bit):
vectorized_result = 1.0 - 2.0 * np.float64(random_bit)
return vectorized_result
def product(random_bit):
mapped_result = 1.0 - 2.0 * random_bit
return mapped_result
np_one_minus_one = np.array([1.0, -1.0]).astype(np.float64)
def _array(random_bit):
mapped_result = np_one_minus_one[random_bit]
return mapped_result
one = np.float64(1)
minus_two = np.float64(-2)
def astype(random_bit):
mapped_result = one + minus_two * random_bit.astype(np.float64)
return mapped_result
function_list = [np_cast, product, _array, astype]
print("start benchmark")
for function in function_list:
_time = timeit.timeit(lambda: function(random_bit), number=100000)
print(f"{function.__name__}: {_time:.3f} seconds")
我有过这样的经历:
np_cast: 178.604 seconds
product: 172.939 seconds
_array: 239.305 seconds
astype: 186.031 seconds