程序 CPU 占用率较高如何排查

Posted by KalosAner on March 14, 2025

一、定位

定位到对应的进程,然后因为线程是 CPU 调度的最小单位,找到进程中的线程。

二、分析

CPU 过高可能的原因:

1、代码逻辑问题:死循环或者时间复杂度过高

2、多线程并发:自旋锁滥用(忙等待持续占用 CPU)

3、频繁内存分配释放,缓存未命中

4、频繁的系统调用

三、解决

对于自旋锁可以优化成互斥锁

内存分配频繁可以使用内存池

缓存未命中通常需要设置线程的亲源性,比如说绑定某一个 CPU

频繁的系统调用可以使用缓冲区避免(比如当 read 时可以使用缓存)

四、案例

#include <thread>
#include <atomic>
#include <vector>
void busy_task() {
	while (true) {
	
	}
}

void slow_algorithm() {
    for (long i = 0; i < 10000000000L; ++ i) {
        volatile = int x = i * i;
    }
}

int main() {
    std::vector<std::thread> threads;
    threads.emplace_back(busy_task);
    threads.emplace_back(slow_algorithm);
    
    for (auto& t : threads) t.join();
    return 0;
}

1、编译

1
g++ -g example.cc -o example -lpthread

2、运行

1
./example

3、定位进程

1
2
# -c 显示进程完成信息
top -c

4、定位线程

1
2
# -H 启用线程模式,-p 指定进程
top -H -p <pid>

5、查看线程堆栈

1
gdb -p <pid> -ex "thread apply all bt" -ex "detach" -ex "quit" > stack_dump.log

6、查看日志

1
cat stack_dump.log