嗯,根据对 shuf 答案的评论,他在一分钟内改组了 78 000 000 000 行。
接受挑战...
编辑:我打破了自己的记录
powershuf 在 0.047 秒内完成
$ time ./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null
./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null 0.02s user 0.01s system 80% cpu 0.047 total
之所以这么快,是因为我没有读取整个文件,只是将文件指针移动 10 次,然后打印指针后面的行。
Gitlab Repo
旧尝试
首先我需要一个 78.000.000.000 行的文件:
seq 1 78 | xargs -n 1 -P 16 -I% seq 1 1000 | xargs -n 1 -P 16 -I% echo "" > lines_78000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000.txt > lines_78000000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000000.txt > lines_78000000000.txt
这给了我一个包含 780 亿 个换行符的文件 ;-)
现在是 shuf 部分:
$ time shuf -n 10 lines_78000000000.txt
shuf -n 10 lines_78000000000.txt 2171.20s user 22.17s system 99% cpu 36:35.80 total
瓶颈是 CPU 并且没有使用多个线程,它将 1 个核心固定为 100%,其他 15 个未使用。
Python 是我经常使用的,因此我将使用它来加快速度:
#!/bin/python3
import random
f = open("lines_78000000000.txt", "rt")
count = 0
while 1:
buffer = f.read(65536)
if not buffer: break
count += buffer.count('\n')
for i in range(10):
f.readline(random.randint(1, count))
这让我不到一分钟:
$ time ./shuf.py
./shuf.py 42.57s user 16.19s system 98% cpu 59.752 total
我在配备 i9 和三星 NVMe 的 Lenovo X1 Extreme 2nd gen 上执行此操作,这为我提供了足够的读写速度。
我知道它可以变得更快,但我会留出一些空间让其他人尝试一下。
线路计数器source: Luther Blissett