本文使用java进程来举例
1. 查看java进程及其线程对cpu的占用情况
首先使用ps -ef找到java进程id
# ps -ef|grep java
然后通过top -p pid命令查看该进程占用的cpu情况,例如:
# top -p 29008
top - 17:17:29 up 6 days, 23:41, 5 users, load average: 0.99, 0.80, 0.66
Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie
Cpu(s): 25.5%us, 0.0%sy, 0.0%ni, 74.5%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 7857876k total, 3429332k used, 4428544k free, 229888k buffers
Swap: 9895928k total, 0k used, 9895928k free, 1512232k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
29008 root 20 0 2427m 773m 9.9m S 102.0 10.1 5:56.72 java
此时,若想查看线程占用cpu的情况,手动输入shift+h (Show threads On)进行显示线程的切换。
我们可以直接使用一个参数就默认打开线程占用CPU的跟踪,使用-H参数,例如:
[root@supervision1 ~]# top -p 29008 -H
top - 17:13:40 up 6 days, 23:37, 5 users, load average: 0.79, 0.58, 0.57
Tasks: 78 total, 1 running, 77 sleeping, 0 stopped, 0 zombie
Cpu(s): 25.6%us, 0.0%sy, 0.0%ni, 74.4%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 7857876k total, 3421196k used, 4436680k free, 229888k buffers
Swap: 9895928k total, 0k used, 9895928k free, 1512200k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
29014 root 25 0 2430m 771m 13m R 99.6 10.1 1:27.41 java
29013 root 16 0 2430m 771m 13m S 1.0 10.1 0:00.73 java
29010 root 16 0 2430m 771m 13m S 0.7 10.1 0:00.73 java
29011 root 16 0 2430m 771m 13m S 0.7 10.1 0:00.71 java
29012 root 16 0 2430m 771m 13m S 0.7 10.1 0:00.70 java
说明:重点查看%CPU一项,查看哪个线程占用的cpu最多,然后找到对应的pid。
top命令的TIME/TIME+是指的进程所使用的CPU时间,不是进程启动到现在的时间,因此,如果一个进程使用的cpu很少,那即使这个进程已经存在N长时间,TIME/TIME+也是很小的数值。
跟踪这个线程所有系统调用
# strace -p 29014
Process 29014 attached - interrupt to quit
mprotect(0x2aaaaad03000, 4096, PROT_READ) = 0
futex(0x46555274, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x46555270, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1
futex(0x4821a4b4, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x4821a4b0, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1
futex(0x2aaab421d528, FUTEX_WAKE_PRIVATE, 1) = 1
clock_gettime(CLOCK_REALTIME, {1432286153, 770906000}) = 0
2. 查看java进程占用内存情况
# cat /proc/23386/status
Name: java
State: S (sleeping)
Tgid: 23386
Pid: 23386
PPid: 1
TracerPid: 0
Uid: 0 0 0 0
Gid: 0 0 0 0
Utrace: 0
FDSize: 256
Groups: 0
VmPeak: 13003444 kB
VmSize: 13003444 kB
VmLck: 0 kB
VmHWM: 311496 kB
VmRSS: 307048 kB
VmData: 12846208 kB
VmStk: 88 kB
VmExe: 32 kB
VmLib: 14256 kB
VmPTE: 1704 kB
VmSwap: 0 kB
Threads: 194
说明:
VmRSS: 307048 kB 表示的就是占用的物理内存。
Threads: 194 表示目前一共打开194个线程。