macoschild-processnstask

Command line tool running slowly from NSTask but fast from Terminal


I have written a cmdline tool that usually takes 15-20 seconds to finish.

While it performs its task, it outputs its progress at least once per second via stdout.

When I run the command from Terminal.app, it performs as fast as possible, e.g. within less than 20s.

But when I run it from my GUI app, via NSTask, the tool takes at least 3-5 times longer.

The GUI app uses an NSPipe with an observer on NSFileHandleReadCompletionNotification to monitor the output from the tool, and that arrives frequently (e.g. at least every second).

I tried to set the NSTask's qualityOfService property to the higher values (up to 0x21) without any improvement.

The task was launched from an thread (invoked via performSelectorInBackground) and waits for the task's completion by calling its waitUntilExit method.

I checked with Activity Monitor:

I've seen the issue on 10.13.6 on two very differently configured computers. I have no yet had the opportunity to test on other OS versions, though if it doesn't work well in 10.13, that's bad enough already anyway.

What could be causing the tool to get throttled like this?

The tool spends most of the time in the kernel, because it invokes searchfs(), which scans the file system extensively. I wonder if that's part of the problem.

Also, can someone suggest alternatives for running the tool in a way that lets the GUI app keep control over its life cycle (i.e. it should be run as a child process), lets it pass arguments to the tool and read its stderr and stdout pipes?


Solution

  • You can always increase the priority of your NSTask by launching it with:

    nice -n *priority* *command* *arguments* 
    

    in which priority must be a negative number up to -20, the more negative it is the higher priority it will get.

    However you will need super user privileges to launch a command like this.

    You can read about it in here:

    https://ss64.com/osx/nice.html

    or here:

    https://superuser.com/questions/42817/is-there-any-way-to-set-the-priority-of-a-process-in-mac-os-x