NumPy内存映射技术详解 轻松处理超大数组不再担心内存溢出问题

什么是NumPy内存映射技术?
NumPy内存映射(Memory Mapping)是一种将磁盘文件直接映射到内存地址空间的技术,它允许程序像访问内存数组一样访问磁盘上的数据,而无需一次性将整个文件加载到RAM中。这项技术特别适合处理超大数据集,因为它能显著降低内存占用,避免内存溢出(Out of Memory)错误。
在传统的数据处理方式中,当我们需要处理一个大型文件(例如几GB甚至几十GB的CSV或二进制文件)时,通常需要将整个文件读入内存。这不仅消耗大量RAM,还可能导致程序崩溃。而内存映射技术通过操作系统虚拟内存管理机制,只在需要时将文件的部分内容加载到内存,实现了按需加载(Lazy Loading)。
NumPy通过
numpy.memmap
类提供内存映射功能,它继承自
numpy.ndarray
,因此拥有NumPy数组的所有特性,包括向量化操作、切片索引等。
内存映射的工作原理
内存映射的核心原理是利用操作系统的虚拟内存系统。当调用
numpy.memmap
时,操作系统会创建一个虚拟地址空间,将磁盘文件与这段地址空间关联起来。程序访问这些地址时,操作系统会自动处理数据的加载和换出。
具体流程如下:
程序请求访问映射地址
CPU发现该地址尚未在物理内存中(触发缺页中断)
操作系统从磁盘读取对应的数据块到物理内存
更新页表,建立虚拟地址到物理地址的映射
程序继续执行,对程序透明
这种机制的优势在于:
按需加载
:只加载实际访问的数据部分
自动换出
:当内存紧张时,操作系统会自动将不常用的数据换出到磁盘
共享内存
:多个进程可以映射同一个文件,实现进程间通信
基本使用方法
1. 创建内存映射数组
import numpy as np
import os

# 定义文件路径和数组形状
filename = ‘large_array.dat’
shape = (10000, 10000) # 1亿个元素,约7.45GB(float64)
dtype = np.float64

# 创建内存映射文件
# mode=’w+’ 表示读写模式,如果文件不存在则创建
fp = np.memmap(filename, dtype=dtype, mode=’w+’, shape=shape)

print(f”创建的内存映射数组形状: {fp.shape}”)
print(f”数组数据类型: {fp.dtype}”)
print(f”文件路径: {fp.filename}”)
print(f”文件大小: {os.path.getsize(filename) / (1024**3):.2f} GB”)
2. 像普通数组一样操作
# 像普通NumPy数组一样操作
# 注意:这些操作会立即写入磁盘,但操作系统可能延迟实际磁盘写入

# 写入数据
fp[0, :] = 1.0 # 第一行设为1.0
fp[:, 0] = 2.0 # 第一列设为2.0
fp[100:200, 100:200] = np.random.rand(100, 100) # 局部区域写入随机值

# 读取数据
print(f”fp[0, 0] = {fp[0, 0]}”) # 应该是2.0(列优先)
print(f”fp[1, 1] = {fp[1, 1]}”) # 应该是1.0(行优先)
print(f”fp[100, 100] = {fp[100, 100]:.4f}”) # 随机值

# 切片操作
sub_array = fp[500:600, 500:600] # 这会返回一个新的内存映射数组视图
print(f”子数组形状: {sub_array.shape}”)
3. 刷新与关闭
# 手动刷新数据到磁盘(操作系统通常会自动处理,但可以手动控制)
fp.flush()

# 关闭映射(重要!)
del fp # 删除引用,触发__del__方法
# 或者显式关闭
# fp.close()
高级使用技巧
1. 只读模式与读写模式
# 只读模式(适合分析已有数据)
fp_readonly = np.memmap(filename, dtype=dtype, mode=’r’, shape=shape)
print(f”只读模式: {fp_readonly.flags.writeable}”) # False

# 读写模式(默认)
fp_readwrite = np.memmap(filename, dtype=dtype, mode=’r+’, shape=shape)

# 创建新文件(如果存在则报错)
fp_new = np.memmap(filename + ‘.new’, dtype=dtype, mode=’w+’, shape=shape)
2. 指定偏移量和形状
# 从文件中间开始映射
# 假设文件前1024字节是头部信息
header_size = 1024
data_shape = (5000, 5000)
data_dtype = np.float32

# offset参数指定从文件开头的字节偏移
fp_partial = np.memmap(filename, dtype=data_dtype, mode=’r+’,
shape=data_shape, offset=header_size)
3. 处理不同数据类型
# 整数类型
int_array = np.memmap(‘int_data.dat’, dtype=np.int32, mode=’w+’, shape=(1000, 1000))

# 复数类型
complex_array = np.memmap(‘complex_data.dat’, dtype=np.complex128, mode=’w+’, shape=(100, 100))

# 结构化数组
dt = np.dtype([(‘x’, np.float64), (‘y’, np.float64), (‘z’, np.int32)])
struct_array = np.memmap(‘struct_data.dat’, dtype=dt, mode=’w+’, shape=(10000,))
性能优化策略
1. 块操作(Chunked Processing)
def process_large_array_chunked(filename, shape, chunk_size=1000):
“””
分块处理大型内存映射数组
“””
# 创建内存映射
fp = np.memmap(filename, dtype=np.float64, mode=’r+’, shape=shape)

# 分块处理
for i in range(0, shape[0], chunk_size):
end_i = min(i + chunk_size, shape[0])
for j in range(0, shape[1], chunk_size):
end_j = min(j + chunk_size, shape[1])

# 读取块数据(会触发磁盘I/O)
chunk = fp[i:end_i, j:end_j]

# 处理块数据(例如:平方运算)
processed_chunk = chunk ** 2

# 写回(如果需要)
fp[i:end_i, j:end_j] = processed_chunk

# 显式释放块内存
del chunk, processed_chunk

# 刷新到磁盘
fp.flush()
del fp

# 使用示例
# process_large_array_chunked(‘large_array.dat’, (10000, 10000), chunk_size=500)
2. 预读取策略
import threading
import time

class PrefetchingMemmap:
“””
预读取内存映射数组,隐藏I/O延迟
“””
def __init__(self, memmap_obj, prefetch_size=100):
self.memmap = memmap_obj
self.prefetch_size = prefetch_size
self.prefetch_buffer = None
self.prefetch_thread = None
self.stop_event = threading.Event()

def start_prefetch(self, start_idx):
“””启动预读取线程”””
def prefetch():
while not self.stop_event.is_set():
# 预读取下一块
end_idx = min(start_idx + self.prefetch_size, self.memmap.shape[0])
self.prefetch_buffer = self.memmap[start_idx:end_idx]
time.sleep(0.1) # 避免过度占用I/O

self.prefetch_thread = threading.Thread(target=prefetch)
self.prefetch_thread.daemon = True
self.prefetch_thread.start()

def get_chunk(self, start_idx):
“””获取预读取的数据”””
end_idx = min(start_idx + self.prefetch_size, self.memmap.shape[0])
if self.prefetch_buffer is not None:
return self.prefetch_buffer
return self.memmap[start_idx:end_idx]

def stop(self):
“””停止预读取”””
self.stop_event.set()
if self.prefetch_thread:
self.prefetch_thread.join()

# 使用示例
# fp = np.memmap(‘large.dat’, dtype=np.float64, mode=’r’, shape=(100000, 100))
# prefetcher = PrefetchingMemmap(fp, prefetch_size=1000)
# prefetcher.start_prefetch(0)
# data = prefetcher.get_chunk(0)
# prefetcher.stop()
3. 使用madvise优化访问模式
import mmap
import numpy as np

def optimize_access_pattern(fp, pattern=’sequential’):
“””
使用madvise提示操作系统访问模式(Linux/Unix)
“””
# 获取底层文件描述符
fd = fp.filename

# 使用mmap模块进行更底层的控制
with open(fp.filename, ‘rb’) as f:
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

# 设置访问模式提示
if pattern == ‘sequential’:
# 顺序访问
mm.madvise(mmap.MADV_SEQUENTIAL)
elif pattern == ‘random’:
# 随机访问
mm.madvise(mmap.MADV_RANDOM)
elif pattern == ‘willneed’:
# 预读取
mm.madvise(mmap.MADV_WILLNEED)
elif pattern == ‘dontneed’:
# 不再需要
mm.madvise(mmap.MADV_DONTNEED)

# 重新包装为NumPy数组
array = np.frombuffer(mm, dtype=fp.dtype).reshape(fp.shape)
return array
实际应用案例
案例1:处理超大规模科学数据
import numpy as np
import os
import time

def simulate_scientific_data():
“””
模拟生成一个10GB的科学数据集
“””
filename = ‘scientific_data.dat’
shape = (5000, 5000, 100) # 2.5亿个元素,约10GB
dtype = np.float64

# 创建内存映射
fp = np.memmap(filename, dtype=dtype, mode=’w+’, shape=shape)

# 分块写入模拟数据(避免一次性占用太多内存)
chunk_size = 100
for i in range(0, shape[0], chunk_size):
end_i = min(i + chunk_size, shape[0])
for j in range(0, shape[1], chunk_size):
end_j = min(j + chunk_size, shape[1])

# 生成模拟数据(例如:物理模拟结果)
chunk = np.random.rand(end_i – i, end_j – j, shape[2])
chunk = np.sin(chunk * 10) * np.cos(chunk * 5) # 复杂的物理公式

fp[i:end_i, j:end_j] = chunk

fp.flush()
del fp
print(f”生成完成,文件大小: {os.path.getsize(filename) / (1024**3):.2f} GB”)

def analyze_scientific_data():
“””
分析科学数据:计算统计特征
“””
filename = ‘scientific_data.dat’
shape = (5000, 5000, 100)
dtype = np.float64

# 只读模式打开
fp = np.memmap(filename, dtype=dtype, mode=’r’, shape=shape)

# 计算全局统计量(分块计算避免内存溢出)
chunk_size = 100
total_sum = 0.0
total_count = 0
global_min = np.inf
global_max = -np.inf

for i in range(0, shape[0], chunk_size):
end_i = min(i + chunk_size, shape[0])
chunk = fp[i:end_i, :, :]

total_sum += np.sum(chunk)
total_count += chunk.size
global_min = min(global_min, np.min(chunk))
global_max = max(global_max, np.max(chunk))

mean = total_sum / total_count

# 计算标准差(需要二次遍历)
variance_sum = 0.0
for i in range(0, shape[0], chunk_size):
end_i = min(i + chunk_size, shape[0])
chunk = fp[i:end_i, :, :]
variance_sum += np.sum((chunk – mean) ** 2)

std = np.sqrt(variance_sum / total_count)

print(f”统计结果:”)
print(f” 均值: {mean:.6f}”)
print(f” 标准差: {std:.6f}”)
print(f” 最小值: {global_min:.6f}”)
print(f” 最大值: {global_max:.6f}”)

del fp

# 执行示例
# simulate_scientific_data()
# analyze_scientific_data()
案例2:图像批处理系统
import numpy as np
import os
from PIL import Image
import struct

class ImageBatchProcessor:
“””
使用内存映射处理大批量图像数据
“””
def __init__(self, image_dir, max_images=10000, img_size=(256, 256)):
self.image_dir = image_dir
self.max_images = max_images
self.img_size = img_size
self.channels = 3 # RGB

# 创建内存映射文件存储图像数据
self.data_file = ‘image_batch.dat’
self.shape = (max_images, img_size[0], img_size[1], self.channels)
self.dtype = np.uint8

# 初始化内存映射
if not os.path.exists(self.data_file):
self._initialize_storage()

def _initialize_storage(self):
“””初始化存储”””
fp = np.memmap(self.data_file, dtype=self.dtype, mode=’w+’, shape=self.shape)
fp[:] = 0 # 初始化为0
fp.flush()
del fp
print(f”初始化存储: {self.data_file}, 大小: {os.path.getsize(self.data_file) / (1024**3):.2f} GB”)

def load_images(self, image_files):
“””批量加载图像到内存映射”””
fp = np.memmap(self.data_file, dtype=self.dtype, mode=’r+’, shape=self.shape)

for idx, img_path in enumerate(image_files[:self.max_images]):
if idx >= self.max_images:
break

try:
# 加载并预处理图像
img = Image.open(img_path).convert(‘RGB’)
img = img.resize(self.img_size)
img_array = np.array(img, dtype=self.dtype)

# 写入内存映射
fp[idx] = img_array

if idx % 100 == 0:
print(f”已加载 {idx}/{len(image_files)} 张图像”)

except Exception as e:
print(f”加载 {img_path} 失败: {e}”)
continue

fp.flush()
del fp
print(“图像加载完成”)

def process_images(self, process_func, batch_size=100):
“””分批处理图像”””
fp = np.memmap(self.data_file, dtype=self.dtype, mode=’r’, shape=self.shape)

results = []
for start_idx in range(0, self.max_images, batch_size):
end_idx = min(start_idx + batch_size, self.max_images)

# 读取批次
batch = fp[start_idx:end_idx]

# 跳过空数据
if np.all(batch == 0):
continue

# 应用处理函数
processed_batch = process_func(batch)
results.append(processed_batch)

print(f”已处理批次 {start_idx//batch_size + 1}”)

del fp
return np.concatenate(results, axis=0) if results else np.array([])

def get_image(self, idx):
“””获取单张图像”””
fp = np.memmap(self.data_file, dtype=self.dtype, mode=’r’, shape=self.shape)
img = fp[idx].copy() # 复制以避免映射关闭后失效
del fp
return img

# 使用示例
def preprocess_batch(batch):
“””图像预处理:归一化和增强”””
# 归一化到 [0, 1]
batch_float = batch.astype(np.float32) / 255.0

# 简单的图像增强:亮度调整
enhanced = batch_float * 1.1
enhanced = np.clip(enhanced, 0, 1)

# 转换回uint8
return (enhanced * 255).astype(np.uint8)

# 模拟图像文件列表
# image_files = [f’img_{i}.jpg’ for i in range(5000)]
# processor = ImageBatchProcessor(‘.’, max_images=5000, img_size=(224, 224))
# processor.load_images(image_files)
# processed = processor.process_images(preprocess_batch, batch_size=200)
案例3:金融时间序列分析
import numpy as np
import pandas as pd
from datetime import datetime, timedelta

class FinancialTimeSeries:
“””
使用内存映射存储和分析大规模金融时间序列
“””
def __init__(self, symbol, start_date, end_date, interval=’1min’):
self.symbol = symbol
self.start_date = datetime.strptime(start_date, ‘%Y-%m-%d’)
self.end_date = datetime.strptime(end_date, ‘%Y-%m-%d’)
self.interval = interval

# 计算数据点数量
self._calculate_points()

# 创建内存映射文件
self.filename = f'{symbol}_tickdata.dat’
self.dtype = np.dtype([
(‘timestamp’, ‘u8’), # Unix时间戳
(‘open’, ‘f8’),
(‘high’, ‘f8’),
(‘low’, ‘f8’),
(‘close’, ‘f8’),
(‘volume’, ‘u4’)
])

if not os.path.exists(self.filename):
self._generate_data()

def _calculate_points(self):
“””计算数据点数量”””
days = (self.end_date – self.start_date).days + 1
if self.interval == ‘1min’:
points_per_day = 24 * 60 # 24小时,60分钟
elif self.interval == ‘5min’:
points_per_day = 24 * 12
else:
points_per_day = 24 * 60 # 默认1分钟

self.total_points = days * points_per_day

def _generate_data(self):
“””生成模拟金融数据”””
fp = np.memmap(self.filename, dtype=self.dtype, mode=’w+’, shape=(self.total_points,))

current_price = 100.0
current_time = self.start_date

for i in range(self.total_points):
# 模拟价格变动(随机游走)
change = np.random.normal(0, 0.5)
open_price = current_price
close_price = open_price + change
high_price = max(open_price, close_price) + abs(np.random.normal(0, 0.1))
low_price = min(open_price, close_price) – abs(np.random.normal(0, 0.1))
volume = np.random.randint(1000, 10000)

# 写入数据
fp[i] = (
int(current_time.timestamp()),
open_price,
high_price,
low_price,
close_price,
volume
)

current_price = close_price
current_time += timedelta(minutes=1)

if i % 100000 == 0:
print(f”已生成 {i}/{self.total_points} 条记录”)

fp.flush()
del fp
print(“金融数据生成完成”)

def calculate_moving_average(self, window_size=60):
“””计算移动平均(分块处理)”””
fp = np.memmap(self.filename, dtype=self.dtype, mode=’r’, shape=(self.total_points,))

# 只计算收盘价的移动平均
chunk_size = 10000
ma_values = np.zeros(self.total_points, dtype=np.float64)

for start in range(0, self.total_points, chunk_size):
end = min(start + chunk_size, self.total_points)
chunk = fp[start:end]

# 计算当前块的移动平均
for i in range(len(chunk)):
global_idx = start + i
if global_idx < window_size: ma_values[global_idx] = chunk['close'][:i+1].mean() else: ma_values[global_idx] = chunk['close'][max(0, i-window_size+1):i+1].mean() del fp return ma_values def find_volatility_spikes(self, threshold=2.0): """识别波动率异常点""" fp = np.memmap(self.filename, dtype=self.dtype, mode='r', shape=(self.total_points,)) # 计算收益率 chunk_size = 50000 spikes = [] for start in range(1, self.total_points, chunk_size): end = min(start + chunk_size, self.total_points) chunk = fp[start:end] prev_chunk = fp[max(0, start-1):end-1] if len(chunk) == 0: continue # 计算对数收益率 returns = np.log(chunk['close'] / prev_chunk['close']) # 计算滚动标准差 window = 60 for i in range(len(returns)): if i < window: continue window_returns = returns[i-window:i] volatility = np.std(window_returns) if volatility > threshold:
global_idx = start + i
timestamp = fp[global_idx][‘timestamp’]
spikes.append({
‘index’: global_idx,
‘timestamp’: datetime.fromtimestamp(timestamp),
‘volatility’: volatility,
‘price’: fp[global_idx][‘close’]
})

del fp
return spikes

# 使用示例
# ts = FinancialTimeSeries(‘AAPL’, ‘2023-01-01’, ‘2023-12-31’, ‘1min’)
# ma = ts.calculate_moving_average(window_size=60)
# spikes = ts.find_volatility_spikes(threshold=1.5)
# print(f”发现 {len(spikes)} 个波动率异常点”)
与普通NumPy数组的对比
内存使用对比
import numpy as np
import psutil
import os

def memory_usage_comparison():
“””对比内存映射和普通数组的内存使用”””

# 测试数据大小
shape = (5000, 5000) # 2500万元素,约190MB (float64)

# 1. 普通NumPy数组
print(“=== 普通NumPy数组 ===”)
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024 / 1024 # MB

normal_array = np.random.rand(*shape)
mem_after = process.memory_info().rss / 1024 / 1024

print(f”内存使用: {mem_after – mem_before:.2f} MB”)
print(f”数组大小: {normal_array.nbytes / (1024**2):.2f} MB”)

# 2. 内存映射数组
print(“\n=== 内存映射数组 ===”)
mem_before = process.memory_info().rss / 1024 / 1024

filename = ‘test_memmap.dat’
fp = np.memmap(filename, dtype=np.float64, mode=’w+’, shape=shape)
fp[:] = np.random.rand(*shape) # 分块写入避免内存峰值

mem_after = process.memory_info().rss / 1024 / 1024

print(f”内存使用: {mem_after – mem_before:.2f} MB”)
print(f”文件大小: {os.path.getsize(filename) / (1024**2):.2f} MB”)

# 清理
del fp, normal_array
if os.path.exists(filename):
os.remove(filename)

# 运行对比
# memory_usage_comparison()
性能对比
import time

def performance_benchmark():
“””性能基准测试”””
shape = (10000, 10000)
filename = ‘benchmark.dat’

# 创建测试数据
print(“创建测试数据…”)
fp = np.memmap(filename, dtype=np.float64, mode=’w+’, shape=shape)
fp[:] = np.random.rand(*shape)
fp.flush()
del fp

# 1. 普通数组(全加载)
print(“\n1. 普通数组(全加载):”)
start = time.time()
normal_array = np.fromfile(filename, dtype=np.float64).reshape(shape)
load_time = time.time() – start

start = time.time()
result_normal = normal_array ** 2
compute_time = time.time() – start

print(f” 加载时间: {load_time:.3f}s”)
print(f” 计算时间: {compute_time:.3f}s”)
print(f” 总时间: {load_time + compute_time:.3f}s”)

# 2. 内存映射(分块)
print(“\n2. 内存映射(分块计算):”)
start = time.time()
fp = np.memmap(filename, dtype=np.float64, mode=’r’, shape=shape)
load_time = time.time() – start

start = time.time()
chunk_size = 1000
result_memmap = np.zeros(shape, dtype=np.float64)
for i in range(0, shape[0], chunk_size):
end = min(i + chunk_size, shape[0])
result_memmap[i:end] = fp[i:end] ** 2
compute_time = time.time() – start

print(f” 映射时间: {load_time:.3f}s”)
print(f” 分块计算时间: {compute_time:.3f}s”)
print(f” 总时间: {load_time + compute_time:.3f}s”)

# 验证结果一致性
print(f”\n结果一致性: {np.allclose(result_normal, result_memmap)}”)

# 清理
del fp, normal_array, result_normal, result_memmap
if os.path.exists(filename):
os.remove(filename)

# 运行基准测试
# performance_benchmark()
最佳实践与注意事项
1. 何时使用内存映射
适合场景:
数据集远大于可用内存
只需要访问数据的子集
需要随机访问大型文件
多个进程需要共享数据
不适合场景:
数据集小于内存(普通数组更快)
需要频繁随机写入(可能导致磁盘碎片)
需要复杂的随机访问模式(可能比顺序读取慢)
2. 性能优化建议
def best_practices():
“””
内存映射最佳实践
“””
# 1. 使用合适的块大小
# 块大小应匹配系统页大小(通常4KB)的倍数
import os
page_size = os.sysconf(‘SC_PAGE_SIZE’)
chunk_size = 1024 * 1024 # 1MB块

# 2. 顺序访问优于随机访问
# 如果需要随机访问,尽量批量进行

# 3. 及时清理映射
# 使用del或close()释放资源

# 4. 使用适当的数据类型
# 如果精度允许,使用float32而非float64

# 5. 考虑使用压缩格式
# 对于稀疏数据,考虑使用压缩文件格式

# 6. 监控磁盘I/O
# 使用工具如iostat监控磁盘性能

pass

# 3. 错误处理
def safe_memmap_operations():
“””安全的内存映射操作”””
filename = ‘safe_test.dat’
shape = (1000, 1000)

try:
# 检查磁盘空间
import shutil
free_space = shutil.disk_usage(‘.’).free
required_space = np.dtype(np.float64).itemsize * np.prod(shape)

if free_space < required_space: raise IOError("磁盘空间不足") # 创建内存映射 fp = np.memmap(filename, dtype=np.float64, mode='w+', shape=shape) # 使用上下文管理器确保清理 try: # 执行操作 fp[:] = np.random.rand(*shape) fp.flush() finally: # 确保关闭 del fp except Exception as e: print(f"操作失败: {e}") # 清理部分创建的文件 if os.path.exists(filename): os.remove(filename) # 4. 内存映射与HDF5的结合 def memmap_with_hdf5(): """ 结合HDF5格式使用内存映射 HDF5提供更好的元数据管理和压缩 """ import h5py # 创建HDF5文件 with h5py.File('data.h5', 'w') as f: # 创建数据集 dset = f.create_dataset('large_data', shape=(10000, 10000), dtype='f8', chunks=(1000, 1000), # 分块存储 compression='gzip') # 压缩 # 写入数据 dset[:] = np.random.rand(10000, 10000) # 读取时可以使用内存映射 with h5py.File('data.h5', 'r') as f: # HDF5数据集支持类似内存映射的访问 data = f['large_data'] # 可以像数组一样访问,但按需加载 print(f"数据形状: {data.shape}") print(f"数据类型: {data.dtype}") # 读取子集 subset = data[100:200, 100:200] print(f"子集形状: {subset.shape}") # 5. 多进程处理 def multiprocess_memmap(): """多进程处理内存映射数组""" from multiprocessing import Pool, cpu_count def process_chunk(args): """处理数据块""" filename, start, end, shape, dtype = args fp = np.memmap(filename, dtype=dtype, mode='r', shape=shape) chunk = fp[start:end] result = chunk ** 2 # 示例处理 del fp return result # 创建测试数据 filename = 'multiprocess_test.dat' shape = (10000, 10000) dtype = np.float64 fp = np.memmap(filename, dtype=dtype, mode='w+', shape=shape) fp[:] = np.random.rand(*shape) fp.flush() del fp # 分块并行处理 num_processes = cpu_count() chunk_size = shape[0] // num_processes tasks = [] for i in range(num_processes): start = i * chunk_size end = shape[0] if i == num_processes - 1 else (i + 1) * chunk_size tasks.append((filename, start, end, shape, dtype)) with Pool(num_processes) as pool: results = pool.map(process_chunk, tasks) # 合并结果(如果需要) # final_result = np.concatenate(results, axis=0) # 清理 if os.path.exists(filename): os.remove(filename) print(f"多进程处理完成,使用 {num_processes} 个进程") # 运行示例 # safe_memmap_operations() # memmap_with_hdf5() # multiprocess_memmap() 常见问题与解决方案 1. 内存映射文件无法删除 # 问题:在Windows上,内存映射文件可能无法删除 # 解决方案:确保释放所有引用并关闭映射 import numpy as np import os import gc def safe_cleanup(filename): """安全清理内存映射文件""" # 1. 删除所有引用 # fp = None # 2. 强制垃圾回收 gc.collect() # 3. 等待一段时间(Windows需要) import time time.sleep(0.1) # 4. 尝试删除 try: if os.path.exists(filename): os.remove(filename) print(f"成功删除 {filename}") except PermissionError: print("文件仍被占用,稍后重试") except Exception as e: print(f"删除失败: {e}") 2. 数据一致性问题 # 问题:操作系统可能延迟写入磁盘 # 解决方案:手动刷新 def ensure_data_persistence(): """确保数据持久化""" filename = 'critical_data.dat' shape = (1000, 1000) fp = np.memmap(filename, dtype=np.float64, mode='w+', shape=shape) fp[:] = np.random.rand(*shape) # 确保数据写入磁盘 fp.flush() os.fsync(fp.fileno()) # 强制写入物理磁盘 del fp # 验证数据完整性 fp_check = np.memmap(filename, dtype=np.float64, mode='r', shape=shape) # 可以计算校验和 import hashlib checksum = hashlib.md5(fp_check.tobytes()).hexdigest() print(f"数据校验和: {checksum}") del fp_check 3. 性能下降问题 # 问题:随机访问导致性能下降 # 解决方案:批量访问或预读取 def optimize_random_access(): """优化随机访问性能""" filename = 'random_access_test.dat' shape = (100000, 100) # 创建数据 fp = np.memmap(filename, dtype=np.float64, mode='w+', shape=shape) fp[:] = np.random.rand(*shape) fp.flush() del fp # 不好的做法:逐个随机访问 fp = np.memmap(filename, dtype=np.float64, mode='r', shape=shape) indices = np.random.randint(0, shape[0], 1000) # 慢:每次访问都可能触发磁盘I/O # values = [fp[i] for i in indices] # 好的做法:批量读取 # 先排序索引,然后批量读取 sorted_indices = np.sort(indices) values = fp[sorted_indices] # 连续读取 del fp 总结 NumPy内存映射技术是处理超大规模数据集的强大工具,它通过虚拟内存机制实现了高效的按需加载,避免了内存溢出问题。关键要点: 核心优势 :处理远超内存容量的数据,保持NumPy数组的所有功能 适用场景 :大数据分析、科学计算、图像处理、金融分析等 最佳实践 : 合理分块处理数据 优先顺序访问 及时释放资源 结合其他技术(如HDF5)使用 注意事项 : 确保足够的磁盘空间 注意数据持久化(flush) 处理好跨平台兼容性 监控磁盘I/O性能 通过合理使用内存映射技术,可以轻松处理GB甚至TB级别的数据集,充分发挥NumPy的计算能力,而无需担心内存限制。 # NumPy内存映射技术详解:轻松处理超大数组不再担心内存溢出问题 什么是NumPy内存映射技术? NumPy内存映射(Memory Mapping)是一种将磁盘文件直接映射到内存地址空间的技术,它允许程序像访问内存数组一样访问磁盘上的数据,而无需一次性将整个文件加载到RAM中。这项技术特别适合处理超大数据集,因为它能显著降低内存占用,避免内存溢出(Out of Memory)错误。 在传统的数据处理方式中,当我们需要处理一个大型文件(例如几GB甚至几十GB的CSV或二进制文件)时,通常需要将整个文件读入内存。这不仅消耗大量RAM,还可能导致程序崩溃。而内存映射技术通过操作系统虚拟内存管理机制,只在需要时将文件的部分内容加载到内存,实现了按需加载(Lazy Loading)。 NumPy通过 numpy.memmap 类提供内存映射功能,它继承自 numpy.ndarray ,因此拥有NumPy数组的所有特性,包括向量化操作、切片索引等。 内存映射的工作原理 内存映射的核心原理是利用操作系统的虚拟内存系统。当调用 numpy.memmap 时,操作系统会创建一个虚拟地址空间,将磁盘文件与这段地址空间关联起来。程序访问这些地址时,操作系统会自动处理数据的加载和换出。 具体流程如下: 程序请求访问映射地址 CPU发现该地址尚未在物理内存中(触发缺页中断) 操作系统从磁盘读取对应的数据块到物理内存 更新页表,建立虚拟地址到物理地址的映射 程序继续执行,对程序透明 这种机制的优势在于: 按需加载 :只加载实际访问的数据部分 自动换出 :当内存紧张时,操作系统会自动将不常用的数据换出到磁盘 共享内存 :多个进程可以映射同一个文件,实现进程间通信 基本使用方法 1. 创建内存映射数组 import numpy as np import os # 定义文件路径和数组形状 filename = 'large_array.dat' shape = (10000, 10000) # 1亿个元素,约7.45GB(float64) dtype = np.float64 # 创建内存映射文件 # mode='w+' 表示读写模式,如果文件不存在则创建 fp = np.memmap(filename, dtype=dtype, mode='w+', shape=shape) print(f"创建的内存映射数组形状: {fp.shape}") print(f"数组数据类型: {fp.dtype}") print(f"文件路径: {fp.filename}") print(f"文件大小: {os.path.getsize(filename) / (1024**3):.2f} GB") 2. 像普通数组一样操作 # 像普通NumPy数组一样操作 # 注意:这些操作会立即写入磁盘,但操作系统可能延迟实际磁盘写入 # 写入数据 fp[0, :] = 1.0 # 第一行设为1.0 fp[:, 0] = 2.0 # 第一列设为2.0 fp[100:200, 100:200] = np.random.rand(100, 100) # 局部区域写入随机值 # 读取数据 print(f"fp[0, 0] = {fp[0, 0]}") # 应该是2.0(列优先) print(f"fp[1, 1] = {fp[1, 1]}") # 应该是1.0(行优先) print(f"fp[100, 100] = {fp[100, 100]:.4f}") # 随机值 # 切片操作 sub_array = fp[500:600, 500:600] # 这会返回一个新的内存映射数组视图 print(f"子数组形状: {sub_array.shape}") 3. 刷新与关闭 # 手动刷新数据到磁盘(操作系统通常会自动处理,但可以手动控制) fp.flush() # 关闭映射(重要!) del fp # 删除引用,触发__del__方法 # 或者显式关闭 # fp.close() 高级使用技巧 1. 只读模式与读写模式 # 只读模式(适合分析已有数据) fp_readonly = np.memmap(filename, dtype=dtype, mode='r', shape=shape) print(f"只读模式: {fp_readonly.flags.writeable}") # False # 读写模式(默认) fp_readwrite = np.memmap(filename, dtype=dtype, mode='r+', shape=shape) # 创建新文件(如果存在则报错) fp_new = np.memmap(filename + '.new', dtype=dtype, mode='w+', shape=shape) 2. 指定偏移量和形状 # 从文件中间开始映射 # 假设文件前1024字节是头部信息 header_size = 1024 data_shape = (5000, 5000) data_dtype = np.float32 # offset参数指定从文件开头的字节偏移 fp_partial = np.memmap(filename, dtype=data_dtype, mode='r+', shape=data_shape, offset=header_size) 3. 处理不同数据类型 # 整数类型 int_array = np.memmap('int_data.dat', dtype=np.int32, mode='w+', shape=(1000, 1000)) # 复数类型 complex_array = np.memmap('complex_data.dat', dtype=np.complex128, mode='w+', shape=(100, 100)) # 结构化数组 dt = np.dtype([('x', np.float64), ('y', np.float64), ('z', np.int32)]) struct_array = np.memmap('struct_data.dat', dtype=dt, mode='w+', shape=(10000,)) 性能优化策略 1. 块操作(Chunked Processing) def process_large_array_chunked(filename, shape, chunk_size=1000): """ 分块处理大型内存映射数组 """ # 创建内存映射 fp = np.memmap(filename, dtype=np.float64, mode='r+', shape=shape) # 分块处理 for i in range(0, shape[0], chunk_size): end_i = min(i + chunk_size, shape[0]) for j in range(0, shape[1], chunk_size): end_j = min(j + chunk_size, shape[1]) # 读取块数据(会触发磁盘I/O) chunk = fp[i:end_i, j:end_j] # 处理块数据(例如:平方运算) processed_chunk = chunk ** 2 # 写回(如果需要) fp[i:end_i, j:end_j] = processed_chunk # 显式释放块内存 del chunk, processed_chunk # 刷新到磁盘 fp.flush() del fp # 使用示例 # process_large_array_chunked('large_array.dat', (10000, 10000), chunk_size=500) 2. 预读取策略 import threading import time class PrefetchingMemmap: """ 预读取内存映射数组,隐藏I/O延迟 """ def __init__(self, memmap_obj, prefetch_size=100): self.memmap = memmap_obj self.prefetch_size = prefetch_size self.prefetch_buffer = None self.prefetch_thread = None self.stop_event = threading.Event() def start_prefetch(self, start_idx): """启动预读取线程""" def prefetch(): while not self.stop_event.is_set(): # 预读取下一块 end_idx = min(start_idx + self.prefetch_size, self.memmap.shape[0]) self.prefetch_buffer = self.memmap[start_idx:end_idx] time.sleep(0.1) # 避免过度占用I/O self.prefetch_thread = threading.Thread(target=prefetch) self.prefetch_thread.daemon = True self.prefetch_thread.start() def get_chunk(self, start_idx): """获取预读取的数据""" end_idx = min(start_idx + self.prefetch_size, self.memmap.shape[0]) if self.prefetch_buffer is not None: return self.prefetch_buffer return self.memmap[start_idx:end_idx] def stop(self): """停止预读取""" self.stop_event.set() if self.prefetch_thread: self.prefetch_thread.join() # 使用示例 # fp = np.memmap('large.dat', dtype=np.float64, mode='r', shape=(100000, 100)) # prefetcher = PrefetchingMemmap(fp, prefetch_size=1000) # prefetcher.start_prefetch(0) # data = prefetcher.get_chunk(0) # prefetcher.stop() 3. 使用madvise优化访问模式 import mmap import numpy as np def optimize_access_pattern(fp, pattern='sequential'): """ 使用madvise提示操作系统访问模式(Linux/Unix) """ # 获取底层文件描述符 fd = fp.filename # 使用mmap模块进行更底层的控制 with open(fp.filename, 'rb') as f: mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) # 设置访问模式提示 if pattern == 'sequential': # 顺序访问 mm.madvise(mmap.MADV_SEQUENTIAL) elif pattern == 'random': # 随机访问 mm.madvise(mmap.MADV_RANDOM) elif pattern == 'willneed': # 预读取 mm.madvise(mmap.MADV_WILLNEED) elif pattern == 'dontneed': # 不再需要 mm.madvise(mmap.MADV_DONTNEED) # 重新包装为NumPy数组 array = np.frombuffer(mm, dtype=fp.dtype).reshape(fp.shape) return array 实际应用案例 案例1:处理超大规模科学数据 import numpy as np import os import time def simulate_scientific_data(): """ 模拟生成一个10GB的科学数据集 """ filename = 'scientific_data.dat' shape = (5000, 5000, 100) # 2.5亿个元素,约10GB dtype = np.float64 # 创建内存映射 fp = np.memmap(filename, dtype=dtype, mode='w+', shape=shape) # 分块写入模拟数据(避免一次性占用太多内存) chunk_size = 100 for i in range(0, shape[0], chunk_size): end_i = min(i + chunk_size, shape[0]) for j in range(0, shape[1], chunk_size): end_j = min(j + chunk_size, shape[1]) # 生成模拟数据(例如:物理模拟结果) chunk = np.random.rand(end_i - i, end_j - j, shape[2]) chunk = np.sin(chunk * 10) * np.cos(chunk * 5) # 复杂的物理公式 fp[i:end_i, j:end_j] = chunk fp.flush() del fp print(f"生成完成,文件大小: {os.path.getsize(filename) / (1024**3):.2f} GB") def analyze_scientific_data(): """ 分析科学数据:计算统计特征 """ filename = 'scientific_data.dat' shape = (5000, 5000, 100) dtype = np.float64 # 只读模式打开 fp = np.memmap(filename, dtype=dtype, mode='r', shape=shape) # 计算全局统计量(分块计算避免内存溢出) chunk_size = 100 total_sum = 0.0 total_count = 0 global_min = np.inf global_max = -np.inf for i in range(0, shape[0], chunk_size): end_i = min(i + chunk_size, shape[0]) chunk = fp[i:end_i, :, :] total_sum += np.sum(chunk) total_count += chunk.size global_min = min(global_min, np.min(chunk)) global_max = max(global_max, np.max(chunk)) mean = total_sum / total_count # 计算标准差(需要二次遍历) variance_sum = 0.0 for i in range(0, shape[0], chunk_size): end_i = min(i + chunk_size, shape[0]) chunk = fp[i:end_i, :, :] variance_sum += np.sum((chunk - mean) ** 2) std = np.sqrt(variance_sum / total_count) print(f"统计结果:") print(f" 均值: {mean:.6f}") print(f" 标准差: {std:.6f}") print(f" 最小值: {global_min:.6f}") print(f" 最大值: {global_max:.6f}") del fp # 执行示例 # simulate_scientific_data() # analyze_scientific_data() 案例2:图像批处理系统 import numpy as np import os from PIL import Image import struct class ImageBatchProcessor: """ 使用内存映射处理大批量图像数据 """ def __init__(self, image_dir, max_images=10000, img_size=(256, 256)): self.image_dir = image_dir self.max_images = max_images self.img_size = img_size self.channels = 3 # RGB # 创建内存映射文件存储图像数据 self.data_file = 'image_batch.dat' self.shape = (max_images, img_size[0], img_size[1], self.channels) self.dtype = np.uint8 # 初始化内存映射 if not os.path.exists(self.data_file): self._initialize_storage() def _initialize_storage(self): """初始化存储""" fp = np.memmap(self.data_file, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = 0 # 初始化为0 fp.flush() del fp print(f"初始化存储: {self.data_file}, 大小: {os.path.getsize(self.data_file) / (1024**3):.2f} GB") def load_images(self, image_files): """批量加载图像到内存映射""" fp = np.memmap(self.data_file, dtype=self.dtype, mode='r+', shape=self.shape) for idx, img_path in enumerate(image_files[:self.max_images]): if idx >= self.max_images:
break

try:
# 加载并预处理图像
img = Image.open(img_path).convert(‘RGB’)
img = img.resize(self.img_size)
img_array = np.array(img, dtype=self.dtype)

# 写入内存映射
fp[idx] = img_array

if idx % 100 == 0:
print(f”已加载 {idx}/{len(image_files)} 张图像”)

except Exception as e:
print(f”加载 {img_path} 失败: {e}”)
continue

fp.flush()
del fp
print(“图像加载完成”)

def process_images(self, process_func, batch_size=100):
“””分批处理图像”””
fp = np.memmap(self.data_file, dtype=self.dtype, mode=’r’, shape=self.shape)

results = []
for start_idx in range(0, self.max_images, batch_size):
end_idx = min(start_idx + batch_size, self.max_images)

# 读取批次
batch = fp[start_idx:end_idx]

# 跳过空数据
if np.all(batch == 0):
continue

# 应用处理函数
processed_batch = process_func(batch)
results.append(processed_batch)

print(f”已处理批次 {start_idx//batch_size + 1}”)

del fp
return np.concatenate(results, axis=0) if results else np.array([])

def get_image(self, idx):
“””获取单张图像”””
fp = np.memmap(self.data_file, dtype=self.dtype, mode=’r’, shape=self.shape)
img = fp[idx].copy() # 复制以避免映射关闭后失效
del fp
return img

# 使用示例
def preprocess_batch(batch):
“””图像预处理:归一化和增强”””
# 归一化到 [0, 1]
batch_float = batch.astype(np.float32) / 255.0

# 简单的图像增强:亮度调整
enhanced = batch_float * 1.1
enhanced = np.clip(enhanced, 0, 1)

# 转换回uint8
return (enhanced * 255).astype(np.uint8)

# 模拟图像文件列表
# image_files = [f’img_{i}.jpg’ for i in range(5000)]
# processor = ImageBatchProcessor(‘.’, max_images=5000, img_size=(224, 224))
# processor.load_images(image_files)
# processed = processor.process_images(preprocess_batch, batch_size=200)
案例3:金融时间序列分析
import numpy as np
import pandas as pd
from datetime import datetime, timedelta

class FinancialTimeSeries:
“””
使用内存映射存储和分析大规模金融时间序列
“””
def __init__(self, symbol, start_date, end_date, interval=’1min’):
self.symbol = symbol
self.start_date = datetime.strptime(start_date, ‘%Y-%m-%d’)
self.end_date = datetime.strptime(end_date, ‘%Y-%m-%d’)
self.interval = interval

# 计算数据点数量
self._calculate_points()

# 创建内存映射文件
self.filename = f'{symbol}_tickdata.dat’
self.dtype = np.dtype([
(‘timestamp’, ‘u8’), # Unix时间戳
(‘open’, ‘f8’),
(‘high’, ‘f8’),
(‘low’, ‘f8’),
(‘close’, ‘f8’),
(‘volume’, ‘u4’)
])

if not os.path.exists(self.filename):
self._generate_data()

def _calculate_points(self):
“””计算数据点数量”””
days = (self.end_date – self.start_date).days + 1
if self.interval == ‘1min’:
points_per_day = 24 * 60 # 24小时,60分钟
elif self.interval == ‘5min’:
points_per_day = 24 * 12
else:
points_per_day = 24 * 60 # 默认1分钟

self.total_points = days * points_per_day

def _generate_data(self):
“””生成模拟金融数据”””
fp = np.memmap(self.filename, dtype=self.dtype, mode=’w+’, shape=(self.total_points,))

current_price = 100.0
current_time = self.start_date

for i in range(self.total_points):
# 模拟价格变动(随机游走)
change = np.random.normal(0, 0.5)
open_price = current_price
close_price = open_price + change
high_price = max(open_price, close_price) + abs(np.random.normal(0, 0.1))
low_price = min(open_price, close_price) – abs(np.random.normal(0, 0.1))
volume = np.random.randint(1000, 10000)

# 写入数据
fp[i] = (
int(current_time.timestamp()),
open_price,
high_price,
low_price,
close_price,
volume
)

current_price = close_price
current_time += timedelta(minutes=1)

if i % 100000 == 0:
print(f”已生成 {i}/{self.total_points} 条记录”)

fp.flush()
del fp
print(“金融数据生成完成”)

def calculate_moving_average(self, window_size=60):
“””计算移动平均(分块处理)”””
fp = np.memmap(self.filename, dtype=self.dtype, mode=’r’, shape=(self.total_points,))

# 只计算收盘价的移动平均
chunk_size = 10000
ma_values = np.zeros(self.total_points, dtype=np.float64)

for start in range(0, self.total_points, chunk_size):
end = min(start + chunk_size, self.total_points)
chunk = fp[start:end]

# 计算当前块的移动平均
for i in range(len(chunk)):
global_idx = start + i
if global_idx < window_size: ma_values[global_idx] = chunk['close'][:i+1].mean() else: ma_values[global_idx] = chunk['close'][max(0, i-window_size+1):i+1].mean() del fp return ma_values def find_volatility_spikes(self, threshold=2.0): """识别波动率异常点""" fp = np.memmap(self.filename, dtype=self.dtype, mode='r', shape=(self.total_points,)) # 计算收益率 chunk_size = 50000 spikes = [] for start in range(1, self.total_points, chunk_size): end = min(start + chunk_size, self.total_points) chunk = fp[start:end] prev_chunk = fp[max(0, start-1):end-1] if len(chunk) == 0: continue # 计算对数收益率 returns = np.log(chunk['close'] / prev_chunk['close']) # 计算滚动标准差 window = 60 for i in range(len(returns)): if i < window: continue window_returns = returns[i-window:i] volatility = np.std(window_returns) if volatility > threshold:
global_idx = start + i
timestamp = fp[global_idx][‘timestamp’]
spikes.append({
‘index’: global_idx,
‘timestamp’: datetime.fromtimestamp(timestamp),
‘volatility’: volatility,
‘price’: fp[global_idx][‘close’]
})

del fp
return spikes

# 使用示例
# ts = FinancialTimeSeries(‘AAPL’, ‘2023-01-01’, ‘2023-12-31’, ‘1min’)
# ma = ts.calculate_moving_average(window_size=60)
# spikes = ts.find_volatility_spikes(threshold=1.5)
# print(f”发现 {len(spikes)} 个波动率异常点”)
与普通NumPy数组的对比
内存使用对比
import numpy as np
import psutil
import os

def memory_usage_comparison():
“””对比内存映射和普通数组的内存使用”””

# 测试数据大小
shape = (5000, 5000) # 2500万元素,约190MB (float64)

# 1. 普通NumPy数组
print(“=== 普通NumPy数组 ===”)
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024 / 1024 # MB

normal_array = np.random.rand(*shape)
mem_after = process.memory_info().rss / 1024 / 1024

print(f”内存使用: {mem_after – mem_before:.2f} MB”)
print(f”数组大小: {normal_array.nbytes / (1024**2):.2f} MB”)

# 2. 内存映射数组
print(“\n=== 内存映射数组 ===”)
mem_before = process.memory_info().rss / 1024 / 1024

filename = ‘test_memmap.dat’
fp = np.memmap(filename, dtype=np.float64, mode=’w+’, shape=shape)
fp[:] = np.random.rand(*shape) # 分块写入避免内存峰值

mem_after = process.memory_info().rss / 1024 / 1024

print(f”内存使用: {mem_after – mem_before:.2f} MB”)
print(f”文件大小: {os.path.getsize(filename) / (1024**2):.2f} MB”)

# 清理
del fp, normal_array
if os.path.exists(filename):
os.remove(filename)

# 运行对比
# memory_usage_comparison()
性能对比
import time

def performance_benchmark():
“””性能基准测试”””
shape = (10000, 10000)
filename = ‘benchmark.dat’

# 创建测试数据
print(“创建测试数据…”)
fp = np.memmap(filename, dtype=np.float64, mode=’w+’, shape=shape)
fp[:] = np.random.rand(*shape)
fp.flush()
del fp

# 1. 普通数组(全加载)
print(“\n1. 普通数组(全加载):”)
start = time.time()
normal_array = np.fromfile(filename, dtype=np.float64).reshape(shape)
load_time = time.time() – start

start = time.time()
result_normal = normal_array ** 2
compute_time = time.time() – start

print(f” 加载时间: {load_time:.3f}s”)
print(f” 计算时间: {compute_time:.3f}s”)
print(f” 总时间: {load_time + compute_time:.3f}s”)

# 2. 内存映射(分块)
print(“\n2. 内存映射(分块计算):”)
start = time.time()
fp = np.memmap(filename, dtype=np.float64, mode=’r’, shape=shape)
load_time = time.time() – start

start = time.time()
chunk_size = 1000
result_memmap = np.zeros(shape, dtype=np.float64)
for i in range(0, shape[0], chunk_size):
end = min(i + chunk_size, shape[0])
result_memmap[i:end] = fp[i:end] ** 2
compute_time = time.time() – start

print(f” 映射时间: {load_time:.3f}s”)
print(f” 分块计算时间: {compute_time:.3f}s”)
print(f” 总时间: {load_time + compute_time:.3f}s”)

# 验证结果一致性
print(f”\n结果一致性: {np.allclose(result_normal, result_memmap)}”)

# 清理
del fp, normal_array, result_normal, result_memmap
if os.path.exists(filename):
os.remove(filename)

# 运行基准测试
# performance_benchmark()
最佳实践与注意事项
1. 何时使用内存映射
适合场景:
数据集远大于可用内存
只需要访问数据的子集
需要随机访问大型文件
多个进程需要共享数据
不适合场景:
数据集小于内存(普通数组更快)
需要频繁随机写入(可能导致磁盘碎片)
需要复杂的随机访问模式(可能比顺序读取慢)
2. 性能优化建议
def best_practices():
“””
内存映射最佳实践
“””
# 1. 使用合适的块大小
# 块大小应匹配系统页大小(通常4KB)的倍数
import os
page_size = os.sysconf(‘SC_PAGE_SIZE’)
chunk_size = 1024 * 1024 # 1MB块

# 2. 顺序访问优于随机访问
# 如果需要随机访问,尽量批量进行

# 3. 及时清理映射
# 使用del或close()释放资源

# 4. 使用适当的数据类型
# 如果精度允许,使用float32而非float64

# 5. 考虑使用压缩格式
# 对于稀疏数据,考虑使用压缩文件格式

# 6. 监控磁盘I/O
# 使用工具如iostat监控磁盘性能

pass

# 3. 错误处理
def safe_memmap_operations():
“””安全的内存映射操作”””
filename = ‘safe_test.dat’
shape = (1000, 1000)

try:
# 检查磁盘空间
import shutil
free_space = shutil.disk_usage(‘.’).free
required_space = np.dtype(np.float64).itemsize * np.prod(shape)

if free_space < required_space: raise IOError("磁盘空间不足") # 创建内存映射 fp = np.memmap(filename, dtype=np.float64, mode='w+', shape=shape) # 使用上下文管理器确保清理 try: # 执行操作 fp[:] = np.random.rand(*shape) fp.flush() finally: # 确保关闭 del fp except Exception as e: print(f"操作失败: {e}") # 清理部分创建的文件 if os.path.exists(filename): os.remove(filename) # 4. 内存映射与HDF5的结合 def memmap_with_hdf5(): """ 结合HDF5格式使用内存映射 HDF5提供更好的元数据管理和压缩 """ import h5py # 创建HDF5文件 with h5py.File('data.h5', 'w') as f: # 创建数据集 dset = f.create_dataset('large_data', shape=(10000, 10000), dtype='f8', chunks=(1000, 1000), # 分块存储 compression='gzip') # 压缩 # 写入数据 dset[:] = np.random.rand(10000, 10000) # 读取时可以使用内存映射 with h5py.File('data.h5', 'r') as f: # HDF5数据集支持类似内存映射的访问 data = f['large_data'] # 可以像数组一样访问,但按需加载 print(f"数据形状: {data.shape}") print(f"数据类型: {data.dtype}") # 读取子集 subset = data[100:200, 100:200] print(f"子集形状: {subset.shape}") # 5. 多进程处理 def multiprocess_memmap(): """多进程处理内存映射数组""" from multiprocessing import Pool, cpu_count def process_chunk(args): """处理数据块""" filename, start, end, shape, dtype = args fp = np.memmap(filename, dtype=dtype, mode='r', shape=shape) chunk = fp[start:end] result = chunk ** 2 # 示例处理 del fp return result # 创建测试数据 filename = 'multiprocess_test.dat' shape = (10000, 10000) dtype = np.float64 fp = np.memmap(filename, dtype=dtype, mode='w+', shape=shape) fp[:] = np.random.rand(*shape) fp.flush() del fp # 分块并行处理 num_processes = cpu_count() chunk_size = shape[0] // num_processes tasks = [] for i in range(num_processes): start = i * chunk_size end = shape[0] if i == num_processes - 1 else (i + 1) * chunk_size tasks.append((filename, start, end, shape, dtype)) with Pool(num_processes) as pool: results = pool.map(process_chunk, tasks) # 合并结果(如果需要) # final_result = np.concatenate(results, axis=0) # 清理 if os.path.exists(filename): os.remove(filename) print(f"多进程处理完成,使用 {num_processes} 个进程") # 运行示例 # safe_memmap_operations() # memmap_with_hdf5() # multiprocess_memmap() 常见问题与解决方案 1. 内存映射文件无法删除 # 问题:在Windows上,内存映射文件可能无法删除 # 解决方案:确保释放所有引用并关闭映射 import numpy as np import os import gc def safe_cleanup(filename): """安全清理内存映射文件""" # 1. 删除所有引用 # fp = None # 2. 强制垃圾回收 gc.collect() # 3. 等待一段时间(Windows需要) import time time.sleep(0.1) # 4. 尝试删除 try: if os.path.exists(filename): os.remove(filename) print(f"成功删除 {filename}") except PermissionError: print("文件仍被占用,稍后重试") except Exception as e: print(f"删除失败: {e}") 2. 数据一致性问题 # 问题:操作系统可能延迟写入磁盘 # 解决方案:手动刷新 def ensure_data_persistence(): """确保数据持久化""" filename = 'critical_data.dat' shape = (1000, 1000) fp = np.memmap(filename, dtype=np.float64, mode='w+', shape=shape) fp[:] = np.random.rand(*shape) # 确保数据写入磁盘 fp.flush() os.fsync(fp.fileno()) # 强制写入物理磁盘 del fp # 验证数据完整性 fp_check = np.memmap(filename, dtype=np.float64, mode='r', shape=shape) # 可以计算校验和 import hashlib checksum = hashlib.md5(fp_check.tobytes()).hexdigest() print(f"数据校验和: {checksum}") del fp_check 3. 性能下降问题 # 问题:随机访问导致性能下降 # 解决方案:批量访问或预读取 def optimize_random_access(): """优化随机访问性能""" filename = 'random_access_test.dat' shape = (100000, 100) # 创建数据 fp = np.memmap(filename, dtype=np.float64, mode='w+', shape=shape) fp[:] = np.random.rand(*shape) fp.flush() del fp # 不好的做法:逐个随机访问 fp = np.memmap(filename, dtype=np.float64, mode='r', shape=shape) indices = np.random.randint(0, shape[0], 1000) # 慢:每次访问都可能触发磁盘I/O # values = [fp[i] for i in indices] # 好的做法:批量读取 # 先排序索引,然后批量读取 sorted_indices = np.sort(indices) values = fp[sorted_indices] # 连续读取 del fp 总结 NumPy内存映射技术是处理超大规模数据集的强大工具,它通过虚拟内存机制实现了高效的按需加载,避免了内存溢出问题。关键要点: 核心优势 :处理远超内存容量的数据,保持NumPy数组的所有功能 适用场景 :大数据分析、科学计算、图像处理、金融分析等 最佳实践 : 合理分块处理数据 优先顺序访问 及时释放资源 结合其他技术(如HDF5)使用 注意事项 : 确保足够的磁盘空间 注意数据持久化(flush) 处理好跨平台兼容性 监控磁盘I/O性能 通过合理使用内存映射技术,可以轻松处理GB甚至TB级别的数据集,充分发挥NumPy的计算能力,而无需担心内存限制。