Unexpected sendFile() performance behavior

Hello,
I have been playing around with implementing cat-like utility (mostly to help other people learn).
While doing so i encountered interesting performance characteristic of sendFile() on linux.


I will focus on the static builds, libC builds just link libC and use its allocator.

I am cating a 0.5 GiB file with stdout redirected to a file.
I checked that the code does as expected and counted the syscalls used.


The copy_file_range is a bit suspicious, but I have no idea where it came from.

Code:

const std = @import("std");

// this is not 1:1 mapping of the C code, you could do that but its more common to go the cross platfrorm way
// this implementation will work on single threaded blocking code or with green threads executor (just change the io)
pub fn main(init: std.process.Init.Minimal) !void {
    // create a threaded io
    var single_threaded = std.Io.Threaded.init_single_threaded;
    const io = single_threaded.io();
    // this is really bad general purpose allocator, but its the best we have for single-threaded builds
    const gpa = std.heap.page_allocator;

    // allocate the args as we itterate, on linux it does nothing but for example windows needs them allocated
    var it = try init.args.iterateAllocator(gpa);
    // dont forget to free them
    defer it.deinit();

    // skip the executable name
    _ = it.skip();
    // get the first next arguemnt
    var arg: ?[:0]const u8 = it.next();
    // check if we got any (without this check we could have simpler while below, but no real perf lost here)
    if (arg == null) return error.NoArgumentGiven;

    // setup the buffer for writing (read per 16384 byte chunks), only relevant on sendFile fallback
    var stdout_buf: [16384]u8 = undefined;
    // setup the buffer for reading (read per 16384 byte chunks)
    var file_buf: [16384]u8 = undefined;

    // cwd is static, does not need to be closed, check its doc comment
    const local_dir: std.Io.Dir = .cwd();

    // while we get an argument, unwrap it from optional to name, at the end of loop get next
    while (arg) |name| : (arg = it.next()) {
        // open the file in cwd as read only
        const file = try local_dir.openFile(io, name, .{ .mode = .read_only });
        // dont forget to close it
        defer file.close(io);

        // create the reader backed by the buffer
        var file_reader = file.reader(io, &file_buf);
        // pull out the reader interface
        const reader = &file_reader.interface;

        // create the writer backed by the buffer (you dont close stdout, same as C)
        var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buf);
        // pull out the writer interface
        const writer = &stdout_writer.interface;

        // just let it stream the data from one another till it hits EOF, discard the ammount transfered
        _ = try reader.streamRemaining(writer);
        // dont forget to flush
        try writer.flush();
    }
}
const std = @import("std");

// this is not 1:1 mapping of the C code, you could do that but its more common to go the cross platfrorm way
// this implementation will work on single threaded blocking code or with green threads executor (just change the io)
pub fn main(init: std.process.Init.Minimal) !void {
    // create a threaded io
    var single_threaded = std.Io.Threaded.init_single_threaded;
    const io = single_threaded.io();
    // this is really bad general purpose allocator, but its the best we have for single-threaded builds
    const gpa = std.heap.page_allocator;

    // allocate the args as we itterate, on linux it does nothing but for example windows needs them allocated
    var it = try init.args.iterateAllocator(gpa);
    // dont forget to free them
    defer it.deinit();

    // skip the executable name
    _ = it.skip();
    // get the first next arguemnt
    var arg: ?[:0]const u8 = it.next();
    // check if we got any (without this check we could have simpler while below, but no real perf lost here)
    if (arg == null) return error.NoArgumentGiven;

    // setup the buffer for writing (read per 16384 byte chunks), only relevant on sendFile fallback
    var stdout_buf: [16384]u8 = undefined;

    // while we get an argument, unwrap it from optional to name, at the end of loop get next
    while (arg) |name| : (arg = it.next()) {
        // cwd is static, does not need to be closed, check its doc comment
        const local_dir: std.Io.Dir = .cwd();
        // open the file in cwd as read only
        const file = try local_dir.openFile(io, name, .{ .mode = .read_only });
        // dont forget to close it
        defer file.close(io);

        // create the writer backed by the buffer (you dont close stdout, same as C) stdout is streaming FD, so you save 1 syscall before it figures it out
        var stdout_writer = std.Io.File.stdout().writerStreaming(io, &stdout_buf);
        // pull out the writer interface
        const writer = &stdout_writer.interface;

        // create the reader backed by no buffer, the sendfile fills the writer buffer directly
        var file_reader = file.reader(io, &.{});
        // no need to pull out the reader interface, sendFile takes the File.Reader not Io.Reader

        // this attempts to use more optimal syscalls, if not aviable it falls back to streaming (single buffered one tho.)
        // just let it stream the data from one another till it hits EOF, discard the ammount transfered
        _ = try writer.sendFileAll(&file_reader, .unlimited);
        // dont forget to flush
        try writer.flush();
    }
}

Its compiled with ReleaseFast, native architecture and:

.single_threaded = true,
.unwind_tables = .none,
.strip = true,

Binaries are basically the same size aswell, the sendFIle being larger by like 580 bytes.

My expectation would be that the sendFile would be faster, anyone have any ideas why is it like this?

Robert :blush:

1 Like

I don’t think there should be a big difference between _ = try reader.streamRemaining(writer); and _ = try writer.sendFileAll(&file_reader, .unlimited);. The stream function of a file reader just calls the sendFile function of the writer.

The difference is, if the writer is streaming (File.stdout().writerStreaming()) of positional (File.stdout().writer()).
A positional file writer first tries to use the copy_file_range syscall. If this fails, it either changes to a streaming file writer or a loop of [p]write[v] and [p]read[v] is used (this is slow). Which of these two options is done depends on the error. You probably get a EINVAL, because stdout is not regular file. For EINVAL, std.Io.Threaded sets a flag to not use copy_file_range anymore and returns (For OPNOTSUPP, INVAL and NOSYS, it sets this flag for the whole Io.Threaded, which seems wrong to me for OPNOTSUPP and INVAL, since these errors only indicate, that the specific file/file-system does not support copy_file_range). After this, a loop used.

If this fileWriteFilePositional would return a error.Unseekable, the positional writer would turn into a streaming writer.

A streaming file writer first tries to use the sendfile, which is probably the correct syscall for you to use.

Others might disagree, but I would always use a streaming, if no seeking is required.

1 Like

Well all that streaming and non streaming writer/reader setup only affects whether the sendfile syscall is used. I dont care about that part tho.

Thank you for clarification why copy_file_range happened.

I know that when i force it to not use sendfile syscall it gets much faster, my question is why is kernel level sendfile so much slower than the 16k reads and writes.

My expectation would be that its an possible optimization path, not a regression if it happens.

1 Like

I was looking at this, because it’s interesting, and found that it’s only slower if I leave the old file on disk so the benchmark has to overwrite it. If you delete it across runs, the sendfile version is slightly faster. It seems to have something to do with the timing of page invalidation. I have a suspicion, not measured yet, that the sendfile variant is actually always faster, and then it hangs in program exit, flushing the pages dirtied the sendfile.

3 Likes

copy_file_range should be faster when it can be used. I was finding it always faster in the copy tool I started working on. I never actually measured the difference by how much since I did not care. I cared just to find most optimal way to create file copies.

Can you share the contents of the shell files you use in poop?

Basically they all go like this:

#!/bin/sh

./zig-out/bin/cat-sendFile-linkLibC file > ./out/cat-sendFile-linkLibC.out

PS i always clear the ./out/ before running it (but it has no affect on it on my system)

If you pipe it to a regular file, I would expect the copy_file_range syscall to succeed:

$ strace -c ./loop file > out
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
  0.00    0.000000           0         1           close
  0.00    0.000000           0         1           mmap
  0.00    0.000000           0         1           execve
  0.00    0.000000           0         1           sigaltstack
  0.00    0.000000           0         1           arch_prctl
  0.00    0.000000           0         1           openat
  0.00    0.000000           0         1           prlimit64
  0.00    0.000000           0         2           copy_file_range
------ ----------- ----------- --------- --------- ----------------
100.00    0.000000           0         9           total
$ strace -c ./loop file > /dev/null
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 67.45    0.066214           4     16385           preadv
 32.55    0.031956           1     16384           pwritev
  0.00    0.000004           4         1           close
  0.00    0.000000           0         1           mmap
  0.00    0.000000           0         1           execve
  0.00    0.000000           0         1           sigaltstack
  0.00    0.000000           0         1           arch_prctl
  0.00    0.000000           0         1           openat
  0.00    0.000000           0         1           prlimit64
  0.00    0.000000           0         1         1 copy_file_range
------ ----------- ----------- --------- --------- ----------------
100.00    0.098174           2     32777         1 total

Here ./loop is the first of the two files of your original message, compiled with -Ofast.

Can you check if the way you benchmark cat-streaming-static, there are really 16k reads and writes or if the copy_file_range syscall just succeeds?

I also noticed that in earlier zig versions, copy_file_range was being called two times, I forgot now in which implementation that was, so I swapped to sendFile() in which I can cut that last syscall that was used to confirm all data had been copied:

// Not possible to return more than max_chunk
// If return is less than max_chunk, it means that all the data has been written already.
while (try writer.sendFile(&source_reader, .limited(chunk_size_max)) == chunk_size_max) {}

EDIT: sendFileAll() calls that last syscall.

copy_file_range is the reason, I think. Man page explains why.

It’s much newer than the sendfiile. The key difference is that it can offload the copy to the filesystem or hardware - if it supports it:

copy_file_range() gives filesystems an opportunity to implement “copy acceleration” techniques, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks) or server-side-copy (in the case of NFS).

sendfile was originally intended for writing to sockets.

Before Linux 2.6.33, out_fd must refer to a socket. Since Linux 2.6.33 it can be any file. If it’s seekable, then sendfile() changes the file offset appropriately.

It’s quite possible that it does some optimisation tricks that are great for network sockets, but worse for local file-systems. E.g. it’s doing weird tricks with memory that prevent the CPU caches from doing their job.

May be of interest:
https://unix.stackexchange.com/questions/771238/linux-syscalls-advantage-of-copy-file-range-over-sendfile


Strangely though, when I ran it on my computer I did not get the same sort of problem you did. The exact results depend on what sort of file it was writing to…

I checked each of these with hyperfine and strace.

  • Writing to a file
    • ./zig-out/bin/cat random.bin > out.bin
    • Both programs were equally performant.
    • streamRemaining used copy_file_range.
  • Overwriting file that already exists
    • ./zig-out/bin/cat random.bin > out.bin
    • Took 2x longer.
    • Both programs were equally performant.
    • streamRemaining used copy_file_range.
  • Writing to /dev/null
    • ./zig-out/bin/cat random.bin > /dev/null
    • sendfile was much faster (~5x faster).
    • streamRemaining used preadv / pwritev loop
  • Writing to terminal
    • `./zig-out/bin/cat zero.bin
    • sendfile was slightly slower (~3% longer, in both real-time and CPU time).
    • streamRemaining used preadv / pwritev loop

random.bin = 500 MB file from /dev/random
zero.bin = 650 MB file from /dev/zero

So basically, “it works on my machine”. Filesystem is ext4 on an SSD, in case that’s significant.

5 Likes