0. 简介
我们在之前介绍了使用Valgrind、perf、AddressSanitzer等工具来完成内存泄漏的检测,当然内存泄漏以外还有cpu的占用率变高这类问题。作者在这里提供几个方法来对C++程序中CPU程序占用率高问题排查。
1. pstack堆栈查看
pstack 命令可以监听日志,Linux 系统默认没有这个命令。所以我们需要安装pstack
sudo apt install pstack
在ubuntu下使用apt安装时,可能会出现无法使用的问题,解决方法是:直接在/usr/bin下新建一个名为pstack的脚本文件,并给sudo权限
#!/bin/shif test $# -ne 1; then echo "Usage: `basename $0 .sh` <process-id>" 1>&2 exit 1fiif test ! -r /proc/$1; then echo "Process $1 not found." 1>&2 exit 1fi# GDB doesn't allow "thread apply all bt" when the process isn't# threaded; need to peek at the process to determine if that or the# simpler "bt" should be used.backtrace="bt"if test -d /proc/$1/task ; then # Newer kernel; has a task/ directory. if test `/bin/ls /proc/$1/task | /usr/bin/wc -l` -gt 1 2>/dev/null ; then backtrace="thread apply all bt" fielif test -f /proc/$1/maps ; then # Older kernel; go by it loading libpthread. if /bin/grep -e libpthread /proc/$1/maps > /dev/null 2>&1 ; then backtrace="thread apply all bt" fifiGDB=${GDB:-gdb}# Run GDB, strip out unwanted noise.# --readnever is no longer used since .gdb_index is now in use.$GDB --quiet -nx $GDBARGS /proc/$1/exe $1 <<EOF 2>&1 |set width 0set height 0set pagination no$backtraceEOF/bin/sed -n \ -e 's/^\((gdb) \)*//' \ -e '/^#/p' \ -e '/^Thread/p'
启动:
sudo bash /usr/bin/pstack 27596
然后确保pstack命令被以root权限或者适当的权限运行,并确保目标进程处于可调试状态,可以通过使用gdb或者其他调试工具来设置进程的调试。pstack显示的其实是进程在某一刻的调用栈。
以htop为例,这是我们用pstack调用的结果:
这个是用gdb调用的结果:
按照下面的步骤检查一下线程内部的问题
1.命令:top -c。 输入大写P,top的输出会按使用cpu多少排序
PID就是进程号,我程序的进程号是4918。
1.查看耗CPU的线程号
命令:top -Hp 进程号。 同样输入大写P,top的输出会按使用cpu多少排序。
输入`top -Hp 4918`,展示内容如图:
可以看出PID是4927的线程占到了100%的cpu,我的业务日志是打印线程号的
1.查看耗CPU的任务
上面找到了耗CPU的线程,那这个线程在做什么呢?
看线程在干什么,可以看线程的堆栈,命令是pstack 进程号,会输出所有线程的堆栈信息。
输入pstack 4918,并搜索线程4927的堆栈,展示内容如图:
点击C++ CPU程序占用率高问题排查 - 古月居 可查看全文