保存一张表通常意味着转换:CSV 是文本,pickle 是 Python 自己的格式。Arrow 的文件格式两者都不是,它把缓冲区按内存中的样子原样写出,因此加载只是指向这些字节。几个 GB 的 tick 表可以在几毫秒内打开,因为什么都不用解析;多个进程还可以映射同一个文件,共用操作系统缓存中的一份拷贝。
用通俗的话说这个想法
我们在哪里。 主题 5 在单个进程内让各个库共享内存。这个主题把同样的思路延伸到磁盘和其他进程:IPC 格式就是主题 4 中的缓冲区,外面加一点点封装。Parquet 技能讲的是另一种文件格式,压缩得更狠、存储更省;当打开速度最重要时,应该选 IPC。
请操作系统把文件当作程序内存的一部分暴露出来。页面只在被访问时才加载,并在进程之间共享,因此大文件能立即打开,自身不额外占用内存。
文件:先保存,再用映射或不映射读取
write_feather 写出 Feather 第 2 版文件,它其实就是一个 IPC 文件;lz4 和 zstd 压缩每个缓冲区,用打开速度换体积。read_ipc_file(path, True) 映射该文件并直接在其页面上构建表,所以下面的数字显示没有新增内存分配;而普通读取会把每个字节复制到新分配的内存里。压缩文件不能原地使用:必须先解压。
# Three Feather files of the same table: sizes by codecfor codec in ["uncompressed", "lz4", "zstd"]: print(f"{codec:12} {write_feather(table, codec + '.arrow', codec):>9,} bytes")
uncompressed 1,711,442 bytes lz4 1,111,738 bytes zstd 911,258 bytes
# Read the uncompressed file mapped and then normally, and watch Arrow's allocation counterbefore = pa.total_allocated_bytes()mapped = read_ipc_file("uncompressed.arrow", True)print("mapped: equal", mapped.equals(table), "| new allocation:", pa.total_allocated_bytes() - before, "bytes")before = pa.total_allocated_bytes()copied = read_ipc_file("uncompressed.arrow", False)print("copied: equal", copied.equals(table), "| new allocation:", f"{pa.total_allocated_bytes() - before:,}", "bytes")
mapped: equal True | new allocation: 0 bytes copied: equal True | new allocation: 1,710,592 bytes
流:随时间到来的批
文件需要尾部,所以必须在全部写完后才能结束。流没有尾部:先是模式,然后按顺序是一个个批,随到随读。这正是两个进程之间的套接字或管道,或 tick 数据馈送所需的形态。count_stream_rows 一次只读一个批,从不持有整条流,这正是该格式的意义。
# The bars as an IPC stream in batches of 10,000 rows, then read back one batch at a timewritten = write_stream(table, "bars.stream", 10000)batches, rows = count_stream_rows("bars.stream")print(f"{os.path.getsize('bars.stream'):,} bytes in the stream file | {written} batches written | read back: {batches} batches, {rows} rows")
1,710,872 bytes in the stream file | 5 batches written | read back: 5 batches, 33493 rows
IPC 打开最快,可以原地使用,但文件更大。Parquet 更小,并能按列、行组和统计信息跳过数据,但需要解码。对于同一台机器上多个进程读取的热数据,以及进程间传递批,用 IPC;长期存放的数据湖则用 Parquet。
任务要求
- 1`write_feather` 与 `read_ipc_file`
feather.write_feather(table, path, compression=...);用ipc.open_file(source).read_all()读取,其中source是pa.memory_map(path, "r")或路径。 - 2`write_stream` 与 `count_stream_rows`用
ipc.new_stream(sink, schema),对to_batches(...)的每个切片调用write_batch;读取时迭代ipc.open_stream(source)。
实验:评分内容
4 个任务 · 100 分- 保存 Feather 文件:
write_feather25 分 - 读取,映射或不映射:
read_ipc_file25 分 - 写出批的流:
write_stream25 分 - 逐批读取:
count_stream_rows25 分