Skip to content

Instantly share code, notes, and snippets.

@2bam
Last active July 16, 2023 19:22
Show Gist options
  • Save 2bam/068baeba896ad5584ecdd9220b60963b to your computer and use it in GitHub Desktop.
Save 2bam/068baeba896ad5584ecdd9220b60963b to your computer and use it in GitHub Desktop.
Record battery and cpu status to CSV file every minute until stopped (Linux / Bash)
#
# gnuplot script to show energy and cpu by time from batlog.sh
#
# To run:
# gnuplot -persist batlog.gnuplot
#
set datafile separator ","
set xdata time
my_fmt = "%a %b %d %H:%M:%S %Y"
set timefmt my_fmt
set format x "%tH:%tM:%tS" # In case by some magic it withstands >24hs use total hours
set multiplot layout 2,1
# Read the first timestamp from the dataset
first_time = strptime("%a %b %d %H:%M:%S %Y", system("awk -F, 'NR==2 {print $4}' batdump.txt"))
# Define a custom function to calculate the time delta
time_delta(column) = timecolumn(column, my_fmt) - first_time
set xlabel "Time"
set ylabel "Energy"
plot "batdump.txt" every ::1 using (time_delta(4)):3 with lines title "Battery energy over time"
set ylabel "CPU use"
plot "batdump.txt" every ::1 using (time_delta(4)):6 smooth bezier with lines title "CPU use over time"
unset multiplot
#!/bin/bash
#
# Log battery and cpu status every minute to a CSV file
#
# Stops gracefully pressing Ctrl-C ONCE.
# On end will make a copy with ISO timestamp in case you run it again
# You may need to install the sysstat package to have mpstat
#
# Example output:
# $ cat batdump.txt | column -t -s","
# record-date state energy updated percentage %usr %sys %idle
# Sun Jul 16 17:58:05 UTC 2023 fully-charged 62.32 Sun Jul 16 19:56:51 2023 100% 4.25 1.34 94.34
# Normalize decimals using . instead of ,
export LC_ALL=C
# Find yours using `upower -e`
BATTERY_PATH=/org/freedesktop/UPower/devices/battery_BAT0
FO=batdump.txt
STOP=
rm $FO 2> /dev/null
echo -n "record-date," >> $FO
echo -n "state,energy,updated,percentage," >> $FO
mpstat | awk 'NR==3 {OFS=","; print $3,$5,$12}' >> $FO
stop_script() {
cp $FO batdump-$(date -Iseconds).txt
trap -- SIGINT
echo "\nEXITING. Please wait\n"
STOP=1
}
trap stop_script SIGINT
while [ -z $STOP ]; do
echo -n "$(date -u)," >> $FO
upower -i $BATTERY_PATH | awk '
/^ *state:/ {state=$2}
/^ *percentage:/ {percentage=$2}
/^ *energy: */ {energy=$2}
/^ *updated: */ {updated=""; for (i = 2; i <= NF; i++) updated=updated $i " "; gsub(/\(.*\)/,"",updated);}
END {
OFS=","
ORS=","
print state, energy, updated, percentage
}
' >> $FO
mpstat 5 1 | awk 'NR==4 {OFS=","; print $3,$5,$12}' >> $FO
tail -n1 $FO | column -t -s","
# Run in bg and wait to get SIGINT Thx for the trick https://stackoverflow.com/a/32049811/10060021
# NOTE: mpstat already takes 5 seconds
sleep 55 &
wait
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment