[Solution]CPU Usage Is Too High
Background: Recently, I was developing a C program in Linux and I met an issue – CPU usage is too high. I spent some time to figure it out.
Here, I am going to record this issue and solution for your reference if you also meet the same issue.
Why CPU Usage Is Too High?
Short answer: There are lots of loops and constantly preempting time slices.
Long answer:
Now, I am going to introduce how did I solve this issue.
Step 1:
Using “top -H” command to see the CPU usage for every thread. You can see which thread occpuy more CPU and get the PID of this thread.
Step 2:
Using “sudo strace -p <pid>” command to see what are these threads doing.
You will see most of them are system calls. Maybe You will don’t know what do they mean if you don’t have linux system call concept. But sometimes it is very easy to understand the result.
For example. the below is my case with Pseudo code.
......
while (1) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC,ts);
ts.tv_sec = ts.tv_sec + 10;
pthread_cond_timedwait(cond, mutex, ts);
......
}
......
The first parameter of clock_gettime function means a type of clock. CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn’t affected by changes in the system time-of-day clock.
pthread_cond_timedwait function is used to wait until timeout or condition is OK. If the first parameter condition is meet the requirement, it will be woken up. Otherwise, it will be waiting until the ts is bigger than current time.
When I printed this ts time, It is always a value smaller than current time. so pthread_cond_timedwait can be woken up very quickly because of the timeout. While loop will be executed all the time. which cause CPU usage is particularly high.
Solution
Change clock type from CLOCK_MONOTONIC to CLOCK_REALTIME.
Then, ts will be the system real time. ts = ts + 10 means the while loop will be exectued once in 10 seconds. It will reduce the CPU usage.
For my case, When I used “sudo strace -p <pid>” command, It showd many infomation about pthread_cond_timewait() system call, so I can know there is something wrong in this place. It is very useful to debug CPU usage issue.
I hope it is also very helpful for you.
Have a good day and thank you.
Reference:
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?
pthread_cond_timedwait(3) – Linux man page