shuf: use reservoir-sampling for large or unknown sized inputs
commit20d7bce0f7e57d9a98f0ee811e31c757e9fedfff
authorAssaf Gordon <assafgordon@gmail.com>
Wed, 6 Mar 2013 23:25:49 +0000 (6 18:25 -0500)
committerPádraig Brady <P@draigBrady.com>
Mon, 25 Mar 2013 20:07:14 +0000 (25 20:07 +0000)
tree0c3a560e7bbd16762807e0b2fc28d32670549eff
parent4c49dc823ff7da589ae58d8d8313d38a75fc8f64
shuf: use reservoir-sampling for large or unknown sized inputs

Reservoir sampling optimizes selecting K random lines from large or
unknown-sized input: http://en.wikipedia.org/wiki/Reservoir_sampling
Note this also avoids reading any input when -n0 is specified.

* src/shuf.c (main): Use reservoir-sampling when the number of output
lines is known, and the input size is large or unknown.
(input_size): A new function to get the input size for regular files.
(read_input_reservoir_sampling): New function to read lines from input,
keeping only K lines in memory, replacing lines with decreasing prob.
(write_permuted_output_reservoir): New function to output reservoir.
* tests/misc/shuf-reservoir.sh: An expensive_ test using valgrind to
exercise the reservoir-sampling code.
* tests/local.mk: Reference new test.
* NEWS: Mention the improvement.
NEWS
src/shuf.c
tests/local.mk
tests/misc/shuf-reservoir.sh [new file with mode: 0755]