Last active
March 5, 2024 13:56
-
-
Save baatochan/c92a43c3ccb9b575c6c22aba10fc663a to your computer and use it in GitHub Desktop.
Simple python script for battery power usage analysis on Linux.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Script for battery power usage analysis on Linux. The analysis lasts 1min and reads value every 1s. | |
Author: baatochan | |
""" | |
import os | |
import statistics | |
import sys | |
import time | |
verbose_run = False | |
power_now_exists = False | |
sleep_duration = 1 | |
args = len(sys.argv) - 1 | |
if (args > 0): | |
if (sys.argv[1] == "--verbose" or sys.argv[1] == "-v"): | |
verbose_run = True | |
else: | |
print("Can't recognize the provided argument, running with default settings") | |
if verbose_run: print("Checking if /sys/class/power_supply/BAT0/power_now file exists...") | |
power_now_exists = os.path.isfile("/sys/class/power_supply/BAT0/power_now") | |
if not power_now_exists: | |
print("power_now file does NOT exist, using fallback method which is significantly longer...") | |
sleep_duration = 20 | |
else: | |
if verbose_run: print("power_now file exists...") | |
if verbose_run: print("Sleeping for 5s to start analysis with a delay...") | |
time.sleep(5) | |
values = [] | |
for _ in range(60): | |
if power_now_exists: | |
with open('/sys/class/power_supply/BAT0/power_now') as f: | |
value = f.read().splitlines() | |
value = float(value[0]) | |
else: | |
with open('/sys/class/power_supply/BAT0/current_now') as f: | |
current = f.read().splitlines() | |
with open('/sys/class/power_supply/BAT0/voltage_now') as f: | |
voltage = f.read().splitlines() | |
current = float(current[0]) | |
voltage = float(voltage[0]) | |
value = current * voltage | |
values.append(value) | |
if verbose_run: print("Read", value, "as a current power usage, sleeping for", sleep_duration, "s...") | |
time.sleep(sleep_duration) | |
avg = statistics.fmean(values) | |
median = statistics.median(values) | |
if power_now_exists: | |
avg /= 1000000 # convert uW to W | |
median /= 1000000 | |
else: | |
avg /= 1000000000000 # convert pW to W | |
median /= 1000000000000 | |
if verbose_run: print("The individual values of the power usage were:", *values) | |
print("Average power consumption was:", round(avg, 3), "W, median:", round(median, 3), "W.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment