Skip to content

Example of slowness compared to Bash (while or test problem?) #2007

Closed

Description

@alphapapa

This is relatively quick:

locate $HOME | bash -c 'while read dir; do [[ -d $dir ]] && echo $dir; done'

But this is painfully slow:

function onlyDirs
    while read dir
        test -d $dir; and echo $dir
    end
end

locate $HOME | onlyDirs

Activity

  1. ridiculousfish commented on Apr 2, 2015

    @ridiculousfish
    Member

    I would expect them to take equal amounts of total time, except that fish will fully buffer the output (#1396) so you won't see anything until the command is complete. Does the fish version take more total time, or is it just more time before the first output is printed?

  2. alphapapa commented on Apr 2, 2015

    @alphapapa
    Author

    Thanks for the quick response.

    I'm not noticing the buffering you mentioned--output from Fish seems constant and gradual--but it seems that fish is simply taking a lot longer to do it, both in real time and in CPU time, and is using about 10 times as much memory as Bash.

    $cat testfish.fish 
    #!/usr/bin/fish
    function onlyDirs
            while read dir
                    test -d $dir; and echo $dir
            end
    end
    locate $HOME | onlyDirs
    
    $ cat testbash.sh
    #!/bin/bash
    locate $HOME | bash -c 'while read dir; do [[ -d $dir ]] && echo $dir; done'
    
    $ time ./testfish.fish >/dev/null
    26.77user 16.72system 0:43.35elapsed 100%CPU (0avgtext+0avgdata 37520maxresident)k
    0inputs+104outputs (0major+24078minor)pagefaults 0swaps
    
    $ time ./testbash.sh >/dev/null
    6.56user 7.50system 0:13.86elapsed 101%CPU (0avgtext+0avgdata 3124maxresident)k
    0inputs+0outputs (0major+961minor)pagefaults 0swaps
    

    It's not a big deal really, because I still write most scripts in Bash. The situation here was that I was writing some functions to quickly find directories with find/locate, Percol, and Fish, and I ended up having to pipe through Bash instead of using Fish functions because Fish was so much slower (about 3 times slower wall-time here). (Well, I actually ended up piping through Python scripts, because that was even faster, but the point here is the difference between Bash and Fish. :)

    Thanks.

  3. added this to the fish-future milestone on Apr 2, 2015
  4. ridiculousfish commented on Apr 2, 2015

    @ridiculousfish
    Member

    Thanks, that's very useful. Looking at a sample, we're spending like 25% of our time in pthread_sigmask - very surprising.

  5. ridiculousfish commented on Apr 2, 2015

    @ridiculousfish
    Member

    Ha ha ha, that's because builtin_read reads one byte at a time in the non-interactive case. It is that way in fish 1.x too.

  6. snnw commented on Apr 9, 2015

    @snnw
    Contributor

    Hmm, it looks like reading multiple bytes is not trivial. Challenge accepted, though.

    I was thinking, read N bytes at a time, process up to \n, \0, or eof, then lseek back to the start of the next line. However, we can't seek is stdin is a pipe. Can we just reuse the buffer in that case, and hope nobody notices that we've bitten off more stdin than we can chew? Sounds dangerous...

    I wonder how Bash does this.

  7. snnw commented on Apr 9, 2015

    @snnw
    Contributor

    Actually, Bash is reading one character at a time as well, since this is a pipe (and it can't actually do buffered IO). @ridiculousfish something else must be going on..

  8. ridiculousfish commented on Apr 9, 2015

    @ridiculousfish
    Member

    I'm sure you're right, probably many things are going on :) But this is definitely one of them. For every byte read, fish blocks and then unblocks signals. See read_blocked. That pthread_sigmask call is consuming 25% of the time.

  9. snnw commented on Apr 10, 2015

    @snnw
    Contributor

    We're only blocking SIGCHLD, right? Would it make sense to call pthread_sigmask once per call to builtin_read? Honestly, I don't really understand why SIGCHLD needs to be blocked.

  10. ridiculousfish commented on Apr 10, 2015

    @ridiculousfish
    Member

    Honestly I don't understand why any signals need to be blocked there. That's why I've been afraid to touch it!

    Regarding SIGCHLD specifically, blocking that may have been necessary in the past, but the SIGCHLD handler is now completely trivial so it shouldn't be necessary to block.

    I'm OK with replacing that call to read_blocked, and maybe all such calls, with read_loop (which doesn't block signals) and seeing if anything goes wrong, but not for fish 2.2.

  11. modified the milestones: , fish-future on Jul 27, 2015
  12. ridiculousfish commented on Jul 27, 2015

    @ridiculousfish
    Member

    I want to revisit this one.

  13. pickfire commented on Jul 27, 2015

    @pickfire
    Contributor

    Does fish have the capability of reading multiple character at a time? Will it be in the future?

    If fish and bash is reading one character at the same time, why is bash a lot faster than fish?

  14. ridiculousfish commented on Jul 27, 2015

    @ridiculousfish
    Member

    When I profiled it a lot of it was not the one byte buffer size, but instead manipulating the signal mask for every byte read. I think this can be greatly simplified.

  15. 22 remaining items

  16. krader1961 commented on Dec 31, 2016

    @krader1961
    Contributor

    I used the macOS iprofiler command to trace the syscalls of the simple fish script documented in the original comment for 60 seconds. I then used the Instruments app to read the trace and export it to a CSV file that I then massaged with a python program I threw together. Here are the first few lines of the report:

    Syscall                           #calls   total time     avg time/call
    BSC_read                          266222   478.096122446  0.001795855
    BSC_pthread_sigmask               532411   299.499569213  0.000562535
    BSC_wait4                            531    79.603438088  0.149912313
    BSC_fork                             268    64.290372855  0.239889451
    BSC_stat64                          3223    54.243749031  0.016830204
    BSC_ioctl                           6287     0.006766654  0.000001076
    BSC_mmap                              36     0.000427370  0.000011871
    BSC_open                              24     0.000346700  0.000014446
    BSC_open_nocancel                     12     0.000258872  0.000021573
    BSC_sysctl                             6     0.000152660  0.000025443
    

    Notice that the pthread_sigmask() calls account for approximately 1/3 of the total time. I'm willing to bet that all, or nearly all, of those calls can be eliminated.

  17. krader1961 commented on Jan 1, 2017

    @krader1961
    Contributor

    I reduced the number of paths to the first 100,000 from find $HOME.
    I then timed each shell five times and chose the best elapsed time of
    the five runs:

    git head:              32.05 real        12.23 user        19.90 sys
    w/o pthread_setmask(): 24.13 real         9.90 user        14.32 sys
    bash:                   3.84 real         2.20 user         1.63 sys
    

    So my first attempt at improving the performance of the benchmark in this
    issue reduces the elapsed time 25% (user time 19%, sys time 28%). This
    is still considerably slower than bash as you can see above (now only 6x
    slower rather than 8x). But it's a big step in the right direction.

    Using iprofile => Instruments.app export as CSV => summarize data shows
    that fish is considerably less efficient in its I/O. Specifically, it makes
    a huge number of read() calls to requesting only one byte from the file
    containing the path names. Bash reads the same data in chunks of 128 bytes.

    Consider these two syscall profiles for the first 60 seconds of run time of
    each shell. The fish profile is with my pthread_sigmask() elimination.

    Top ten syscalls, by elapsed time, for bash:

    BSC_stat64                         52677    12.895956498  0.000244812
    BSC_lseek                         105203     8.054019910  0.000076557
    BSC_ioctl                         105260     1.575582580  0.000014968
    BSC_read                           53615     0.106179200  0.000001980
    BSC_write_nocancel                  4023     0.028859836  0.000007174
    BSC_mmap                              32     0.000377230  0.000011788
    BSC_open                              13     0.000340590  0.000026199
    BSC_open_nocancel                      6     0.000135880  0.000022647
    BSC_read_nocancel                     12     0.000112360  0.000009363
    BSC_sysctl                             2     0.000057410  0.000028705
    

    Top ten syscalls, by elapsed time, for my improved fish:

    BSC_read                         1907142   652.282603718  0.000342021
    BSC_fork                            1980   347.755721559  0.175634203
    BSC_wait4                           3960   114.473033227  0.028907332
    BSC_stat64                         22195     0.430642407  0.000019403
    BSC_exit                               1     0.238440000  0.238440000
    BSC_ioctl                          44189     0.042139878  0.000000954
    BSC_mmap                              36     0.000425530  0.000011820
    BSC_open                              24     0.000424160  0.000017673
    BSC_open_nocancel                     12     0.000231060  0.000019255
    BSC_sysctl                             6     0.000150490  0.000025082
    

    Notice that in the same interval bash manages to do more than 2x times as
    many stat() calls. Fish spends most of its time reading one byte at a
    time from stdin while that is inconsequential in the bash profile. And that
    appears to be the most important reason for the difference in performance
    between the two shells. Obviously the forks done by fish are also a factor
    and itself interesting since there shouldn't be any need to call fork()
    for this simple script:

    while read dir
        test -d $dir; and echo $dir
    end
    
  18. krader1961 commented on Jan 2, 2017

    @krader1961
    Contributor

    I've implemented a chunked read implementation. In the table below the results labeled "w/perf improvements" includes both the reduced signal manipulation improvements plus the chunked read enhancement. That yields a 72% reduction in run time. We're now only 2.4x slower than bash versus 8.3x slower with the git head version of fish. Not great but a damn sight better. I'd be satisfied if we were within a factor of 2x.

    git head:              32.05 real        12.23 user        19.90 sys
    w/o pthread_setmask(): 24.13 real         9.90 user        14.32 sys
    w/perf improvements:    9.03 real         6.26 user         2.81 sys
    bash:                   3.84 real         2.20 user         1.63 sys
    
  19. krader1961 commented on Jan 2, 2017

    @krader1961
    Contributor

    The instrumented syscall summary for the fish version labeled "w/perf improvements" in my previous comment looks like this:

    BSC_read                           93531    13.990190326  0.000149578
    BSC_wait4                           1969    12.372290710  0.006283540
    BSC_ioctl                         100208    12.253727625  0.000122283
    BSC_lseek                          99466     6.365717475  0.000063999
    BSC_fork                             982     3.525459389  0.003590081
    BSC_stat64                         50180     0.295604777  0.000005891
    BSC_mmap                              36     0.000385300  0.000010703
    BSC_open                              24     0.000347520  0.000014480
    BSC_open_nocancel                     12     0.000231910  0.000019326
    BSC_sysctl                             6     0.000156380  0.000026063
    

    TBD is where the fork() calls are coming from given that the benchmark does not require any external commands.

  20. krader1961 commented on Jan 2, 2017

    @krader1961
    Contributor

    The fork() calls are, according to fish -d2 due to

    <2> fish: Fork #1, pid 23676: internal builtin for 'echo'
    

    I have absolutely no idea why the main thread would fork to execute a builtin command. If we got rid of that fork fish would be reasonably close to bash on this benchmark.

    Running the benchmark under fish -d5 shows the reason for the fork has to do with whether or not it produces output:

    <3> fish: Skipping fork: no output for internal builtin 'read'
    <3> fish: Set status of read dir to 0 using short circuit
    <3> fish: Job is constructed
    <4> fish: Continue job 2, gid 0 (read dir), COMPLETED, NON-INTERACTIVE
    <4> fish: Exec job 'test -d $dir' with id 2
    <3> fish: Skipping fork: no output for internal builtin 'test'
    <3> fish: Set status of test -d $dir to 0 using short circuit
    <3> fish: Job is constructed
    <4> fish: Continue job 2, gid 0 (test -d $dir), COMPLETED, NON-INTERACTIVE
    <4> fish: Exec job 'and echo $dir' with id 2
    <2> fish: Fork #10, pid 23966: internal builtin for 'echo'
    <3> fish: Job is constructed
    <4> fish: Continue job 2, gid 23956 (and echo $dir), UNCOMPLETED, NON-INTERACTIVE
    

    This is another manifestation of issue #1396: fish buffering the output of not just functions but blocks in general. Fixing that is far outside the scope of this issue.

  21. ridiculousfish commented on Jan 3, 2017

    @ridiculousfish
    Member

    fish probably forks echo's output because it's got a redirection. There's some complicated logic here (see redirection_is_to_real_file and its uses) and I suspect it's not actually quite right - there may be fd redirections that make it do the wrong thing. Not forking is hard.

  22. krader1961 commented on Jan 3, 2017

    @krader1961
    Contributor

    Yes, the actual benchmark is doing

    while read dir
        test -d $dir; and echo $dir
    end < data > onlydirs.fish.out
    

    I still don't see why that needs to fork. The relevant comment in src/exec.cpp says we have to fork so that the file will be truncated even if the block produces no output. But that seems rather silly since the truncation should have been done when the redirection was setup. I'm guessing that if I look at the code more closely I'll see that it is deferring the opening of the file for some reason. In any event I think that's a problem for another day. Specifically, after the code in that module has been refactored to eliminate most of the oclint complexity warnings.

    Right now I'd simply like as many people to build and run a fish with this patch as possible. Even if just for a few minutes or hours. I'm nervous that the change to how signals are managed might only exhibit problems in the face of extensive use of the trap command, --on-event functions, or similar mechanisms that I'm unlikely to exercise (much) on my systems.

  23. modified the milestones: fish 2.5.0, on Jan 6, 2017
  24. krader1961 commented on Jan 15, 2017

    @krader1961
    Contributor

    I'm going to close this because the two most significant improvements to the scenario discussed in this issue have been merged. Note that one of the improvements is gated on the variable FISH_NO_SIGNAL_BLOCK being defined so that we can gain confidence it does not introduce any regressions without causing problems for users willing to build from source but not willing to use possibly risky behavior. Hopefully we'll have enough confidence that aspect of the change is correct it can become the default behavior for the 2.6.0 release.

  25. ridiculousfish commented on Jan 21, 2017

    @ridiculousfish
    Member

    One thing I noticed is that ctrl-C is less reliable with FISH_NO_SIGNAL_BLOCK set, for this code: while true ; echo derp > /dev/null; end . It's always been a little flaky but this amplifies it. Time to track it down I guess.

  26. alphapapa commented on Jan 28, 2017

    @alphapapa
    Author

    Kurtis, fantastic work on this, thanks so much. If I have time, I'll see if I can test with the env var set as you described.

  27. locked as resolved and limited conversation to collaborators on Apr 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions