First, CPU utilization rate calculation
CPU usage can be obtained through the top command or the/proc/<pid>/stat file
The following are the parameters for calculating CPU utilization:
pid=17184 |
process number |
utime=45010 |
|
stime=4050 |
When the task is running at the kernel, the unit is jiffies |
cutime=0 |
The time that all dead threads run in the user state, in jiffies |
cstime=0 |
All the time that has died in the nuclear mentality, in jiffies |
#参考python包psutil源码def cpu_percent (Self, interval=none): Def timer (): Return Time.time () * st1 = timer () PT1 = Self._proc.cpu_times () time.sleep (interval) st2 = timer () pt2 = Self._proc.cpu_times () Delta_proc = ( Pt2.user-pt1.user) + (pt2.system-pt1.system) Delta_time = St2-st1 try:cpu_percent = ((delta_proc/delt A_time) * except Zerodivisionerror:return 0.0
Single-Process CPU usage calculation:
① Each process snapshot is a 4-tuple (Utime, stime, Cutime, cstime);
② sampling two short enough time intervals for process snapshots
③ Compute CPU Usage for this process PCPU = 100* (processcputime2–processcputime1)/(TOTALCPUTIME2–TOTALCPUTIME1)
Second, the control principle
Assuming a given total time of 100ms, it is necessary to limit the CPU usage of process a to 25%. The execution time of process A is 25ms, and the remaining time is not allowed for process a to execute. The Sigstop/sigcont in the Linux interrupt signal allows the process to be paused and activated so that the program's CPU usage can be controlled at will.
#参考python包psutil源码def cpu_percent (Self, interval=none): Def timer (): Return Time.time () * st1 = timer () PT1 = Self._proc.cpu_times () time.sleep (interval) st2 = timer () pt2 = Self._proc.cpu_times () Delta_proc = ( Pt2.user-pt1.user) + (pt2.system-pt1.system) Delta_time = St2-st1 try:cpu_percent = ((delta_proc/delt A_time) * except Zerodivisionerror:return 0.0
Research tasks accurately control process CPU usage