Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/base/node/cpuUsage.sh
3296 views
1
#!/bin/bash
2
3
function get_total_cpu_time() {
4
# Read the first line of /proc/stat and remove the cpu prefix
5
CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
6
7
# Sum all of the values in CPU to get total time
8
for VALUE in "${CPU[@]}"; do
9
let $1=$1+$VALUE
10
done
11
}
12
13
TOTAL_TIME_BEFORE=0
14
get_total_cpu_time TOTAL_TIME_BEFORE
15
16
# Loop over the arguments, which are a list of PIDs
17
# The 13th and 14th words in /proc/<PID>/stat are the user and system time
18
# the process has used, so sum these to get total process run time
19
declare -a PROCESS_BEFORE_TIMES
20
ITER=0
21
for PID in "$@"; do
22
if [ -f /proc/$PID/stat ]
23
then
24
PROCESS_STATS=`cat /proc/$PID/stat`
25
PROCESS_STAT_ARRAY=($PROCESS_STATS)
26
27
let PROCESS_TIME_BEFORE="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}"
28
else
29
let PROCESS_TIME_BEFORE=0
30
fi
31
32
PROCESS_BEFORE_TIMES[$ITER]=$PROCESS_TIME_BEFORE
33
((++ITER))
34
done
35
36
# Wait for a second
37
sleep 1
38
39
TOTAL_TIME_AFTER=0
40
get_total_cpu_time TOTAL_TIME_AFTER
41
42
# Check the user and system time sum of each process again and compute the change
43
# in process time used over total system time
44
ITER=0
45
for PID in "$@"; do
46
if [ -f /proc/$PID/stat ]
47
then
48
PROCESS_STATS=`cat /proc/$PID/stat`
49
PROCESS_STAT_ARRAY=($PROCESS_STATS)
50
51
let PROCESS_TIME_AFTER="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}"
52
else
53
let PROCESS_TIME_AFTER=${PROCESS_BEFORE_TIMES[$ITER]}
54
fi
55
56
PROCESS_TIME_BEFORE=${PROCESS_BEFORE_TIMES[$ITER]}
57
let PROCESS_DELTA=$PROCESS_TIME_AFTER-$PROCESS_TIME_BEFORE
58
let TOTAL_DELTA=$TOTAL_TIME_AFTER-$TOTAL_TIME_BEFORE
59
CPU_USAGE=`echo "$((100*$PROCESS_DELTA/$TOTAL_DELTA))"`
60
61
# Parent script reads from stdout, so echo result to be read
62
echo $CPU_USAGE
63
((++ITER))
64
done
65
66