TOC

GNU/Linux 上如何快速创建一个大文件?「from StackOverflow」

StackOverflow 上看到好些种快速创建文件的命令,逐个测试,在 Ubuntu 下可用的方法有以下几种:

time dd if=/dev/zero of=test.img bs=10M iflag=fullblock,count_bytes count=10G
# 0.00s user 0.45s system 1% cpu 39.144 total

# 在 xfsprogs 包中:
# -n 表示不写入数据
time xfs_mkfile -n 10g test.img
# 0.01s user 0.01s system 2% cpu 0.669 total

# 在 VBox 挂载的虚拟磁盘上执行时遇到 “不支持的操作” 错误
# 在 EXT4 磁盘上没有遇到问题,速度很快
time fallocate -l 10G test.img

time truncate -s 10G test.img
# 0.00s user 0.00s system 46% cpu 0.005 total

time dd if=/dev/zero of=test.img bs=1 count=0 seek=10G
# 0.00s user 0.00s system 77% cpu 0.002 total

最后看到的 dd seek 方案深得征信深得朕心。

根据这个思路,Python 创建 10G 的文件应该这么写(也是我一直以来的写法):

GB = 1 << 30
with open('test.img', 'w') as _file:
    _file.seek(10 * GB - 1)
    _file.write(chr(0))