The introduction

  • Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Perhaps the most familiar aspect of CPU performance is not the CONTEXT switch of CPU, nor the load of CPU mentioned above. The first thing that probably comes to mind is CPU usage. Yes, how much CPU is used can be seen intuitively. But do you know exactly where CPU usage comes from? Let’s take you through it today.

Clock cycle

As mentioned repeatedly before, Linux has the multi-process, multi-task characteristics, so the CPU is sliced according to time, ensure that each process can execute, but the execution must end when the time is up, that is, the CPU context switch, but how to specify this time? Which brings us to the CPU clock cycle.

Baidu defines it this way: We only need to look at the key parts:

The clock period is the reciprocal of the clock base frequency in a synchronous circuit. What was the base frequency of the clock at that time? It was the beat of the clock (expressed as HZ in the kernel), which was used to trigger time interrupts, and internally maintained the global variable Jiffies, which increased its count by one each time an interrupt occurred.

/boot/config/timer/timer/timer/timer/timer/timer

The permission is readable and writable, there are two files do not know which one, this time can be opened one by one, also can use the command to open, here we use the command to find:

Grep ‘CONFIG_HZ=’ /boot/config-$(uname -r), where grep is the pipe, ‘CONFIG_HZ=’ is the variable we look for, and /boot/config-$(uname -r) is the file location.

I can’t access the kernel in userspace, so what should I do? The kernel provides a user-space beat rate USER_HZ, which is fixed at 100 and the time period is 1/100 of a second.

CPU tasks and statistics

/proc/stat = /proc/stat = /proc/stat = /proc/stat = /proc/stat

cat /proc/stat | grep ^cpu

You can see that there are four core cpus, the top is the total number of cpus, then the specific parameters of each CPU, the left is the CPU number, and then the total number of CPU beats in different scenarios, in USER_HZ, of course you do not need to remember.

Of course,/proc/statThe system has been running since the start of the system and kernel statistics, let us know:

The indicators are described as follows:

CPU utilization, that is, in addition to the free time in the other time the percentage of the total CPU time, it doesn’t make any sense to direct calculation, our statistics tools are generally calculated difference every once in a while to get the CPU usage, so we pay attention in the use of performance analysis tools of statistical interval set, must be the same.