Linux utime folder3/2/2024 So, the 14th column in the /proc/$PID/stat file becomes the 13th index in the array. This is because Bash has zero-based arrays. We can notice we use the index 13, 14, and 21 instead of 14, 15, and 22. If the process’s name has whitespaces and we don’t account for that situation, it would change the meaning of each column in the /proc/$PID/stat file.Īfter that, we get the process’s utime, stime, and starttime from the PROCESS_STAT array and store them into individual variables. We do this because the process’s name is placed inside parentheses and it can have whitespaces. We use the sed command to substitute anything in between parenthesis with an X character. Then, we read the process’s status from the /proc/$PID/stat file and store it into an array. Now, let’s review some parts of the previous Bash script.įirst of all, we check if the script receives the process’s ID as a parameter. And then, the script prints the CPU usage as a percentage of the elapsed time since the process started. So, the process has used 6% of CPUĪs we can see, the script displayed all the information for the process ID 4396.įirst, the script prints how much CPU time in seconds the process has used. The PID 4396 has spent 416s in user mode, 126s in kernel mode. Let’s write a Bash script called total_cpu_usage.sh to perform the calculation: #!/bin/bash This way, we can easily calculate the total CPU usage of a process. Finally, we calculate the elapsed time since the process started and divide the sum of utime and stime by the elapsed time. Then, we convert the process’s values from clock ticks to seconds. First, we get the process’s utime, stime, and starttime, and the system’s uptime. We can split the CPU usage calculation into three steps. As the system’s uptime is in seconds, we have to convert the clock ticks to seconds to calculate the process’s CPU usage. Instead, they are in units called clock ticks. However, the process’s utime, stime, and starttime are not in seconds. Now, we know how to calculate the total CPU usage. Let’s see the content of /proc/uptime: $ cat /proc/uptime The first value is the system’s uptime in seconds. We can get the system’s uptime by reading the /proc/uptime file. So, we can calculate the elapsed time by subtracting the process’s starttime from the system’s uptime. The process’s starttime is measured since the system booted. This value is the 22nd column from the /proc//stat file and is called starttime. To get the elapsed time since the process started, we can use the process’s start time. So, the total CPU usage of an application is the sum of utime and stime, divided by the elapsed time. Usually, we represent the CPU usage as a percentage of the elapsed time since the process started.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |