如何查看进程进行了多少次上下文切换?

lun*_*ain 33 linux shell process

我想看看我的进程是否进行了很多上下文切换。我还想看看操纵任务组如何影响上下文切换的数量。

小智 41

您可以在 中查看有关进程上下文切换的信息/proc/<pid>/status

$ pid=307
$ grep ctxt /proc/$pid/status
voluntary_ctxt_switches:        41
nonvoluntary_ctxt_switches:     16
Run Code Online (Sandbox Code Playgroud)

要查看这些数字不断更新,请运行

$ # Update twice a second.
$ watch -n.5 grep ctxt /proc/$pid/status
Run Code Online (Sandbox Code Playgroud)

要获得数字,请运行

$ grep ctxt /proc/$pid/status | awk '{ print $2 }'
Run Code Online (Sandbox Code Playgroud)


poi*_*ige 13

pidstat(1) - 报告 Linux 任务的统计信息。根据man pidstat这很简单pidstat -w …


Bra*_*ram 5

请参阅man getrusage,它可以让您查询自愿和非自愿上下文切换的数量。

struct rusage {
           struct timeval ru_utime; /* user CPU time used */
           struct timeval ru_stime; /* system CPU time used */
           long   ru_maxrss;        /* maximum resident set size */
           long   ru_ixrss;         /* integral shared memory size */
           long   ru_idrss;         /* integral unshared data size */
           long   ru_isrss;         /* integral unshared stack size */
           long   ru_minflt;        /* page reclaims (soft page faults) */
           long   ru_majflt;        /* page faults (hard page faults) */
           long   ru_nswap;         /* swaps */
           long   ru_inblock;       /* block input operations */
           long   ru_oublock;       /* block output operations */
           long   ru_msgsnd;        /* IPC messages sent */
           long   ru_msgrcv;        /* IPC messages received */
           long   ru_nsignals;      /* signals received */
           long   ru_nvcsw;         /* voluntary context switches */
           long   ru_nivcsw;        /* involuntary context switches */
};
Run Code Online (Sandbox Code Playgroud)

您可以告诉它报告每个线程的信息,如下所示:

struct rusage usage;
getrusage( RUSAGE_THREAD, &usage );
Run Code Online (Sandbox Code Playgroud)

只需在关键部分之前和之后调用它两次,然后查看 use.ru_nivcsw 值是否增加。