基于这问题,我想以一秒的频率将特定进程的性能记录到csv
(逗号分隔值)日志文件中。
就像是:
timestamp(unix),cpu_activity(%),mem_usage(B),network_activity(B)
1355407327,24.6,7451518,345
1355407328,27.6,7451535,12
1355407329,31.6,7451789,467
...
答案1
我试图获取 rx_bytes 和 tx_bytes 但没有运气,其他东西正在工作..所以你可以使用下面的脚本进行相同的操作
#!/bin/bash
# /sys/class/net/eth0/statistics/rx_bytes
# /sys/class/net/eth0/statistics/tx_bytes
Process="$1"
[[ -z $2 ]] && InterVal=1 || InterVal=$2
show_help() {
cat <<_EOF
Usage :
$0 <ProcessName> <Interval (Default 1s)>
_EOF
}
Show_Process_Stats() {
pgrep "${Process}" >/dev/null 2>&1 || { echo "Error: Process($1) it not Running.."; exit 1;};
while :
do
# timestamp(unix),cpu_activity(%),mem_usage(B),network_activity(B)
timestamp=$(date +%s)
read cpu_activty mem_usage < <( ps --no-headers -o %cpu,rssize -C "${Process}" )
echo "${timestamp}","${cpu_activty}","${mem_usage}"
sleep $InterVal
done
}
Main() {
case $1 in
""|-h|--help)
show_help
;;
*)
Show_Process_Stats
;;
esac
}
Main $*
答案2
rx 和 tx 应该如何计算?我尝试了以下操作,请检查并告诉我们您想要完成什么。
#!/bin/bash
# /sys/class/net/eth0/statistics/rx_bytes
# /sys/class/net/eth0/statistics/tx_bytes
Process="$1"
[[ -z $2 ]] && InterVal=1 || InterVal=$2
show_help() {
cat <<_EOF
Usage :
$0 <ProcessName> <Interval (Default 1s)>
_EOF
}
Show_Process_Stats() {
pgrep "${Process}" >/dev/null 2>&1 || { echo "Error: Process($1) it not Running.."; exit 1;};
old_rx=0
old_tx=0
echo "timestamp,cpu_activty,mem_usage,rx_bytes,tx_bytes"
while :
do
# timestamp(unix),cpu_activity(%),mem_usage(B),network_activity(B)
timestamp=$(date +%s)
raw_rx_bytes=$(< /sys/class/net/eth0/statistics/rx_bytes )
raw_tx_bytes=$(< /sys/class/net/eth0/statistics/tx_bytes )
rx_bytes=$(( $raw_rx_bytes - $old_rx ))
tx_bytes=$(( $raw_tx_bytes - $old_tx ))
read cpu_activty mem_usage < <( ps --no-headers -o %cpu,rssize -C "${Process}" )
echo "${timestamp}","${cpu_activty}","${mem_usage}","${rx_bytes}","${tx_bytes}"
old_rx=${raw_rx_bytes}
old_tx=${raw_tx_bytes}
sleep $InterVal
done
}
Main() {
case $1 in
""|-h|--help)
show_help
;;
*)
Show_Process_Stats
;;
esac
}
Main $*