man unix/sort

How sort(1) sorts more data than fits in memory

lib / Unix tools 11 mindraft

checked against: Apple text_cmds-199, sort 2.3-Apple (201)

sort can sort a file larger than your RAM. Nothing magic happens. It sorts what fits, writes it to a temporary file, and merges those files at the end. The interesting parts are the numbers. How much does it keep in memory before spilling? Where do the files go? How many does it merge at once? And why does the same command run ten times faster with LC_ALL=C?

The sort on my Mac (macOS 27.2.1, Apple M2 Pro, 16 GB) prints 2.3-Apple (201) for --version. It is FreeBSD’s sort, written by Gabor Kovesdan (2009) and Oleg Moskalenko (2012), carried in Apple’s text_cmds project. Apple builds the version string from the project version, which points to text_cmds-201. Apple has not published that tag. I read text_cmds-199, the newest one, and its sort.c, file.c and coll.c are byte-for-byte the same as in text_cmds-190.0.1. Where a claim about the installed binary comes with no experiment, it comes from that source. GNU coreutils sort is not installed here, so what I say about it comes from reading its source at tag v9.12 only.

What POSIX promises

Not much about memory. The POSIX.1-2024 page for sort lists -m, -o, -c, -C, -u, the ordering options and -k. There is no -S for memory and no -T for a temporary directory. The only hint that temporary files exist is the TMPDIR environment variable, which shall “override the default directory for temporary files, if any”.

The plan: sorted runs, then a merge

input ──► read lines until the budget is full ──► sort them ──► .bsdsort.PID.0
          read lines until the budget is full ──► sort them ──► .bsdsort.PID.1
          ...                                                   ...
          last lines (still in memory)        ──► sort them ──► .bsdsort.PID.114

merge 15 files at a time into new temp files until fewer than 16 remain,
then merge those into the output

The reading loop is procfile in file.c. It adds each line to a list and checks the list’s memsize after every line. When memsize reaches available_free_memory, it sorts the list, writes it to a new temporary file and empties the list. At end of input, if any file was written, the rest of the list becomes one more file and merge_files takes over. If none was written, the list is sorted and printed directly.

How big is the budget

set_hw_params in sort.c asks sysconf for the number of physical pages and the page size, multiplies them, and halves the result:

free_memory = (unsigned long long) pages * (unsigned long long) psize;
available_free_memory = free_memory / 2;

Half of physical RAM, whatever else is running. --debug prints it:

$ echo x | sort --debug | head -2
Memory to be used for sorting: 8589934592
Number of CPUs: 12

8 GiB on a 16 GB Mac. -S changes the budget. parse_memory_buffer_value reads a number and a suffix, and the switch falls through from Y down to K, multiplying by 1024 at each step. A bare number takes the '\0' case, which also multiplies by 1024, so -S 100 means 100 KiB. -S 50% means half of the default budget. --debug agrees:

$ echo x | sort -S 100 --debug | head -1
Memory to be used for sorting: 102400
$ echo x | sort -S 50% --debug | head -1
Memory to be used for sorting: 4294967296

The temporary directory is /var/tmp (the initial value of tmpdir in file.c), replaced by $TMPDIR if it is set and by -T. With TMPDIR unset, a spilling sort did leave .bsdsort. files in /var/tmp. On my Mac TMPDIR points to a per-user folder under /var/folders. new_tmp_file_name builds each name from .bsdsort., the process ID and a counter.

Watching it spill

I made a test file of 2,000,000 random numbers (13,778,004 bytes), forced a 1 MiB budget, and listed the temporary directory every 50 ms. Input comes through a pipe that stays open for one extra second, so the reading phase and the merge phase are easy to tell apart. The names start with a dot, so the listing needs ls -A. This is watch.sh:

(cat big.txt; sleep 1) | TMPDIR=$PWD/tmpd sort -S 1M > sorted.txt &
prev=
for i in $(seq 1 80); do
  sleep 0.05
  cur="$(ls -A tmpd | wc -l | tr -d ' ') files, max index $(ls -A tmpd | awk -F. '{print $NF}' | sort -n | tail -1)"
  [ "$cur" != "$prev" ] && echo "$((i * 50))ms: $cur"
  prev=$cur
done
wait
$ awk 'BEGIN { srand(1); for (i = 0; i < 2000000; i++) print int(rand() * 1000000) }' > big.txt
$ sh watch.sh
50ms: 3 files, max index 3
100ms: 7 files, max index 7
150ms: 11 files, max index 11
...
1400ms: 112 files, max index 111
1450ms: 114 files, max index 113
2150ms: 115 files, max index 115
2200ms: 116 files, max index 115
2300ms: 102 files, max index 116
2450ms: 88 files, max index 117
2550ms: 74 files, max index 118
2700ms: 60 files, max index 119
2850ms: 46 files, max index 120
2950ms: 32 files, max index 121
3100ms: 18 files, max index 122
3150ms: 8 files, max index 122
3900ms: 0 files, max index 

During reading, a new file appears about every 13 ms. In a second run I counted the lines in every file before end of input. Each held between 17,474 and 17,479 lines, about 120 KB of text. A 1 MiB budget holds only 120 KB of input because memsize counts the list’s bookkeeping too. That comes to 60 bytes per line, for lines of about 7 bytes. At that rate the default 8 GiB budget would hold roughly 1 GB of such lines before the first spill. Files 0 to 113 are written while reading, and the last chunk becomes file 114 at end of input.

Then the count drops by 14 at each step. That is shrink_file_list. While there are at least max_open_files files (16), it merges groups of max_open_files - 1 = 15 into a new temporary file and deletes the 15 inputs. 115 runs become 8 files (numbers 115 to 122), and the final merge of those 8 writes the output. Every file is gone when sort exits. The output checks out with sort -c sorted.txt.

Spilling uses far less memory and, here, a little less time:

$ /usr/bin/time -l sort big.txt 2>&1 >/dev/null | grep -E 'real|maximum resident'
        4.48 real         4.37 user         0.09 sys
           160972800  maximum resident set size
$ /usr/bin/time -l sort -S 1M big.txt 2>&1 >/dev/null | grep -E 'real|maximum resident'
        3.86 real         3.74 user         0.10 sys
             3342336  maximum resident set size

161 MB against 3.4 MB. These are single runs, so I read the time only as “not slower”.

How each run is sorted

sort_list_to_file picks the algorithm. The default, DEFAULT_SORT_ALGORITHM in file.h, is SORT_MERGESORT, which calls the C library’s mergesort(3). Its man page says it is stable and “optimized for data with pre-existing order”. There is one exception. If the locale is C or POSIX (byte_sort, set in set_locale) and the first key uses none of -M, -R, -V, -g, -h or -n, the default becomes SORT_RADIXSORT. That is an MSD radix sort in radixsort.c. It distributes lines into 256 buckets by one byte at a time, and hands any bucket of fewer than 65 lines, or any line still tied after 16 bytes, to mergesort.

The locale also changes how two lines compare. With byte_sort, bwscoll uses memcmp. In a multibyte locale such as UTF-8, each line is stored as wide characters and compared with wcscoll, which applies the locale’s collation rules. My locale is en_CA.UTF-8:

$ echo x | sort --debug | sed -n '3,4p'
Using collate rules of en_CA.UTF-8 locale
sort_method=mergesort
$ echo x | LC_ALL=C sort --debug | sed -n '3,5p'
Using collate rules of C locale
Byte sort is used
sort_method=radixsort

The four combinations on big.txt, one run each:

$ for cmd in 'sort' 'sort --radixsort' 'env LC_ALL=C sort --mergesort' 'env LC_ALL=C sort'; do
>   printf '%-32s' "$cmd"
>   /usr/bin/time -p $cmd big.txt 2>&1 >/dev/null | awk '/real/ { print $2 " s" }'
> done
sort                            4.42 s
sort --radixsort                1.67 s
env LC_ALL=C sort --mergesort   1.17 s
env LC_ALL=C sort               0.44 s

Both changes matter, and they multiply. Collation costs about four times with either algorithm, and the radix sort saves between two and three times in either locale. The default in a UTF-8 locale is the slowest of the four, ten times slower than the default in C. For this file of ASCII digits both locales produce identical output (same MD5), so here LC_ALL=C is free speed.

Threads, but not in a pipe

Apple builds sort with SORT_THREADS (see xcconfigs/sort.xcconfig), and set_hw_params sets the thread count to the number of CPUs, capped at 32. Then, near the end of main:

if ((argc < 1) || (strcmp(outfile, "-") == 0) || (*outfile == 0))
        nthreads = 1;

No file arguments means reading stdin, and outfile is "-" unless you pass -o. So a sort in the middle of a pipeline never uses threads. With a file and -o it does, once the list has at least MT_SORT_THRESHOLD (10,000) lines:

$ /usr/bin/time -p sort big.txt > /dev/null
real 4.36
user 4.29
sys 0.05
$ /usr/bin/time -p sort -o out.txt big.txt
real 1.89
user 4.52
sys 0.08

Same work, 2.3 times faster in wall-clock time. --debug also forces one thread.

Ties

POSIX says that lines whose keys compare equal “shall be ordered as if none of the options -d, -f, -i, -n, or -k were present (but with -r still in effect, if it was specified) and with all bytes in the lines significant to the comparison”. In coll.c that is top_level_str_coll, called when the keys tie and -s was not given. It swaps its arguments only if the global -r is set. An r inside -k does not count:

$ printf '   9 812\n   9 7777\n   9 99\n   9 100\n' | LC_ALL=C sort -rn
   9 99
   9 812
   9 7777
   9 100
$ printf '   9 812\n   9 7777\n   9 99\n   9 100\n' | LC_ALL=C sort -k1,1nr
   9 100
   9 7777
   9 812
   9 99

The tie order is by bytes, so 99 beats 812. sort -k1,1nr and sort -rn are not interchangeable when you then take the first few lines. -s turns the last resort off and keeps equal lines in input order.

GNU sort, from its source

I can’t run GNU sort here. Reading src/sort.c at coreutils v9.12, the same plan has different numbers:

  • DEFAULT_TMPDIR is /tmp, and temporary names end in /sortXXXXXX.
  • NMERGE_DEFAULT is 16 files per merge, changeable with --batch-size.
  • default_sort_size takes the larger of available memory and an eighth of total memory, caps it at three quarters of total memory and at half the RLIMIT_DATA and RLIMIT_AS limits.
  • It uses up to DEFAULT_MAX_THREADS = 8 threads.
  • Its in-memory sort is its own merge sort, sequential_sort. A comment says it needs room “for only 1.5*N lines, rather than the usual 2*N lines”, a trick it credits to Knuth’s exercise 5.2.4-10 and to “D. A. Bell, Comp J. 1 (1958), 75”.
  • --compress-program can compress the temporary files.

Curious facts

  • -n never converts to a number. read_number copies up to 128 digits (MAX_NUM_SIZE) as characters and compares the strings, so it orders integers beyond 2⁵³ exactly. -g converts to a double. Fed 9007199254740993 then 9007199254740992, sort -ns swaps them into the right order and sort -gs keeps the input order, because as doubles the two are equal. (-s turns off the whole-line tie-break described above, which would otherwise hide the difference.)
  • -S with no suffix is in kibibytes. -S 1000000 asks for about 1 GB.
  • The temporary files are dotfiles. My first experiment found “no temporary files” because I listed the directory with plain ls.
  • In a pipeline, sort never writes its first line before reading its last one. A head -3 after it only saves the writing, and sort dies of SIGPIPE when it writes into the closed pipe (exit status 141 in bash’s PIPESTATUS).
  • Seventh Edition Unix sort (1979) worked in 32 KiB (#define MEM (16*2048)), tried /usr/tmp before /tmp for files named stm plus the process ID plus aa, and merged 7 files at a time (#define N 7).

History

  • 1979: Seventh Edition Unix sort.c: 32 KiB working space, temporary files in /usr/tmp or /tmp, 7-way merges.
  • 1988: the first year in GNU sort.c’s copyright line.
  • 2009 and 2012: copyright years of Gabor Kovesdan and Oleg Moskalenko on FreeBSD’s sort.c.
  • text_cmds-97 (dated 8 March 2016 in Apple’s repository): Apple still ships GNU sort, with its “Copyright (C) 1988, 1991-2005 Free Software Foundation” header.
  • text_cmds-99 (dated 10 November 2016): Apple’s sort directory is FreeBSD’s, with version string 2.3-Apple. Later tags append the project version, as in 2.3-Apple (201).
  • 2024: POSIX.1-2024 still specifies no memory or temporary-directory option for sort.

Sources

ls unix/