python - 分配和复制 Numpy 数组的异常时间
问题描述
我最近在 Numpy 数组的分配和复制中观察到一个问题:
数组分配需要恒定的时间(wrt.数组大小);将另一个数组的内容复制到分配的数组中,也需要一些时间,这会随着数组大小的增加而增加。但是,问题在于执行分配和复制这两个操作所花费的时间不仅仅是其中任何一个操作的时间总和(见下图):
t(allocation + copy) > t(allocation) + t(copy)
.
我看不出经过额外时间的原因(随着大小迅速增加)。
这是我用于计时的代码。计时是在使用 Intel Core i3 CPU (2.13 GHz) 的 Debian Stretch 下执行的。
import numpy as np
import gc
from timeit import default_timer as timer
import matplotlib.pyplot as plt
def time_all(dim1):
N_TIMES = 10
shape = (dim1, dim1)
data_1 = np.empty(shape, np.int16)
data_2 = np.random.randint(0, 2**14, shape, np.int16)
# allocate array
t1 = timer()
for _ in range(N_TIMES):
data_1 = np.empty(shape, np.int16)
alloc_time = (timer() - t1) / N_TIMES
# copy array
t1 = timer()
for _ in range(N_TIMES):
data_1[:] = data_2
copy_time = (timer() - t1) / N_TIMES
# allocate & copy array
t1 = timer()
for _ in range(N_TIMES):
data_3 = np.empty(shape, np.int16)
np.copyto(data_3, data_2)
alloc_copy_time = (timer() - t1) / N_TIMES
return alloc_time, copy_time, alloc_copy_time
#END def
# measure elapsed times
gc.disable() # disable automatic garbage collection
times_elapsed = np.array([(size, ) + time_all(size)
for size in np.logspace(2, 14, 1<<8,
endpoint=True, base=2, dtype=int)])
gc.enable()
# plot results
plt.plot(times_elapsed[:,0], times_elapsed[:,1], marker='+', lw=0.5, label="alloc")
plt.plot(times_elapsed[:,0], times_elapsed[:,2], marker='+', lw=0.5, label="copy")
plt.plot(times_elapsed[:,0], times_elapsed[:,3], marker='+', lw=0.5, label="alloc©")
plt.xlabel("array dim.")
plt.legend()
plt.savefig("alloc_copy_time.svg")
解决方案
推荐阅读
- python - 我如何只允许我的朋友看到我的帖子
- typescript - 如何增加类型化的 npm 模块类型?
- html - 带有表格的 div 内的滚动条
- machine-learning - Keras - 具有经常丢失的 GRU 层 - 损失:'nan',准确度:0
- python - Pip 根本没有安装
- c++ - ARM GCC C++14 POD 类型未放入 ROM
- javascript - 如何在material-ui react中管理多文本字段验证?
- spring-cloud - Spring cloud-config-server Git-Backend on AWS ECS
- javascript - 我们在哪里可以定义 React 中 Material-UI 的主题
- php - 如何拆分 $content 以接收