On an AMD Ryzen 7 3700X running GNU/Linux:

    $ timeout 30 taskset 1 ./src/shuf-prev \
        -r -i 1000000-1000000 | pv -r > /dev/null
    [ 302MiB/s]
    $ timeout 30 taskset 1 ./src/shuf \
        -r -i 1000000-1000000 | pv -r > /dev/null
    [ 434MiB/s]

* src/shuf.c (print_number): New function.
(write_permuted_numbers, write_random_numbers): Use it.
---
 src/shuf.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)

diff --git a/src/shuf.c b/src/shuf.c
index 948ee88f3..526d0a2dd 100644
--- a/src/shuf.c
+++ b/src/shuf.c
@@ -316,6 +316,18 @@ write_permuted_lines (size_t n_lines, char *const *line,
   return 0;
 }
 
+/* Print NUMBER followed by EOLBYTE to standard output.
+   Return false on failure, true on success.  */
+static bool
+print_number (unsigned long int number, char eolbyte)
+{
+  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
+  char const *p = umaxtostr (number, buf);
+  buf[sizeof buf - 1] = eolbyte;
+  idx_t len = buf + sizeof buf - p;
+  return fwrite (p, 1, len, stdout) == len;
+}
+
 /* Output N_LINES of numbers to stdout, from PERMUTATION array.
    PERMUTATION must have at least N_LINES elements.  */
 static int
@@ -325,9 +337,7 @@ write_permuted_numbers (size_t n_lines, size_t lo_input,
   for (size_t i = 0; i < n_lines; i++)
     {
       unsigned long int n = lo_input + permutation[i];
-      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
-      if (fputs (umaxtostr (n, buf), stdout) < 0
-          || fputc (eolbyte, stdout) < 0)
+      if (! print_number (n, eolbyte))
         return -1;
     }
 
@@ -345,9 +355,7 @@ write_random_numbers (struct randint_source *s, size_t 
count,
   for (size_t i = 0; i < count; i++)
     {
       unsigned long int j = lo_input + randint_choose (s, range);
-      char buf[INT_BUFSIZE_BOUND (uintmax_t)];
-      if (fputs (umaxtostr (j, buf), stdout) < 0
-          || fputc (eolbyte, stdout) < 0)
+      if (! print_number (j, eolbyte))
         return -1;
     }
 
-- 
2.54.0


Reply via email to