了解numpy memmap的性能

Chr*_*isB 5 python performance numpy

我试图更好地理解numpy的memmap如何处理非常大的文件的视图.下面的脚本打开一个内存映射的2048 ^ 3数组,并复制它的下采样128 ^ 3视图

import numpy as np
from time import time

FILE = '/Volumes/BlackBox/test.dat'
array = np.memmap(FILE, mode='r', shape=(2048,2048,2048), dtype=np.float64)

t = time()
for i in range(5):
    view = np.array(array[::16, ::16, ::16])
t = ((time() - t) / 5) * 1000
print "Time (ms): %i" % t
Run Code Online (Sandbox Code Playgroud)

通常,这打印Time (ms): 80左右.但是,如果我将视图分配更改为

view = np.array(array[1::16, 2::16, 3::16])
Run Code Online (Sandbox Code Playgroud)

并运行三次,我得到以下内容:

Time (ms): 9988
Time (ms): 79
Time (ms): 78
Run Code Online (Sandbox Code Playgroud)

有人理解为什么第一次调用要慢得多吗?

Jon*_*nts 5

操作系统仍有部分(或全部)可用的映射文件缓存在物理 RAM 中。初始读取必须访问磁盘,这比访问 RAM 慢很多。做足够多的其他磁盘 IO,你会发现你会更接近你的原始时间,操作系统必须重新读取它没有再次从磁盘缓存的位......