Skip to content

Instantly share code, notes, and snippets.

@osipxd
Last active February 7, 2024 19:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osipxd/0e0d3372aeceaeb6f68e7364b704b5a7 to your computer and use it in GitHub Desktop.
Save osipxd/0e0d3372aeceaeb6f68e7364b704b5a7 to your computer and use it in GitHub Desktop.
Print current Mac wattage (with accuracy up to minute)
#!/usr/bin/env bash
set -euo pipefail
function extract_float_field() {
field=$1
ioreg -rw0 -c AppleSmartBattery |
grep BatteryData |
sed -E "s/.*\"$field\"=([0-9]+).*/\1/" |
xargs -I % lldb --batch --source-quietly --one-line "print/f %" | # Convert IEEE-754 float
grep --only-matching --extended-regexp '[0-9]+(\.[0-9]+)?'
}
printf -- 'Charging (watt): '
extract_float_field AdapterPower
printf -- 'Consumption (watt): '
extract_float_field SystemPower
@glatzg
Copy link

glatzg commented Feb 5, 2024

This works fine on an Intel Mac.

On a M1, M2 or M3 machine the script needs some adjustments due to xargs yielding slightly different output:

(lldb) print/f 1095450523
(int) 12.7030287

Hence the lines 11 and 12 need to be changed to:

        grep -o '(int) [0-9.]*' |
        sed 's/(int) //'

@osipxd
Copy link
Author

osipxd commented Feb 7, 2024

This works fine on an Intel Mac.
On a M1, M2 or M3 machine the script needs some adjustments due to xargs yielding slightly different output:

Thank you! Just revised the script to make it not relying on lldb output format. However, I've not tested it on an Intel Mac. Will you be able to test it there?

@glatzg
Copy link

glatzg commented Feb 7, 2024

Thanks, the script outputs the wattage nicely on an Intel based MacBook Pro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment