首页 > 解决方案 > 分配和复制 Numpy 数组的异常时间

问题描述

我最近在 Numpy 数组的分配和复制中观察到一个问题:

数组分配需要恒定的时间(wrt.数组大小);将另一个数组的内容复制到分配的数组中,也需要一些时间,这会随着数组大小的增加而增加。但是,问题在于执行分配和复制这两个操作所花费的时间不仅仅是其中任何一个操作的时间总和(见下图):

t(allocation + copy) > t(allocation) + t(copy).

我看不出经过额外时间的原因(随着大小迅速增加)。

Numpy分配+复制

这是我用于计时的代码。计时是在使用 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&copy")
plt.xlabel("array dim.")
plt.legend()
plt.savefig("alloc_copy_time.svg")

标签: pythonarraysnumpytime

解决方案


推荐阅读