5

According to man ps:

   -p pidlist
          Select by PID.  This selects the processes whose process ID
          numbers appear in pidlist.  Identical to p and --pid.

   -q pidlist
          Select by PID (quick mode).  This selects the processes
          whose process ID numbers appear in pidlist.  With this
          option ps reads the necessary info only for the pids listed
          in the pidlist and doesn't apply additional filtering
          rules. The order of pids is unsorted and preserved. No
          additional selection options, sorting and forest type
          listings are allowed in this mode.  Identical to q and
          --quick-pid.

I see that -q is considerably faster than -p, taking at most one quarter the time to produce an identical listing.

For example:

$ time ps -fq "$$"
UID        PID  PPID  C STIME TTY          TIME CMD
vagrant   8115  3337  0 23:05 pts/0    00:00:00 bash

real    0m0.003s
user    0m0.001s
sys 0m0.002s
$ time ps -fp "$$"
UID        PID  PPID  C STIME TTY          TIME CMD
vagrant   8115  3337  0 23:05 pts/0    00:00:00 bash

real    0m0.013s
user    0m0.003s
sys 0m0.009s
$

On another system, I observed ps -q to take less than a tenth the time of ps -p.

However, I'm not using a forest-type listing, and I've only passed a single PID so the sorting isn't taking any time (and sorting should be negligible anyway for moderately short PID lists). There are no additional filtering rules in my command.

What all is ps -p doing that ps -q is not?

2

2 Answers 2

8

What I can answer exactly is: What exactly ps -q PID does not do?

  • Sort and/or select a tree from the process list given.

From add -q/q/--quick-pid option with bolding added:

This commit introduces a new option q/-q/--quick-pid to the 'ps' command. The option does a similar job to the p/-p/--pid option (i.e. selection of PIDs listed in the comma separated list that follows the option), but the new option is optimized for speed. In cases where users only need to specify a list of PIDs to be shown and don't need other selection options, forest type output and sorting options, the new option is recommended as it decreases the initial processing delay by avoiding reading the necessary information from all the processes running on the system and by simplifying the internal filtering logic.

The option is designed to be fast.

0
6

I confirmed using strace that ps -fp PID reads information about every process on the system, and ps -fq PID only reads information about one.

This can be confirmed using the following commands:

sudo strace -o /tmp/strace.p.out ps -fp $$
sudo strace -o /tmp/strace.q.out ps -fq $$
ps -e | wc -l
grep -c '"/proc/[0-9]*"' /tmp/strace.{p,q}.out
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.