- Run black to change the coding style in core.py (#188)

- Fix some PEP8 issue in core.py
- Change the default behaviour of set_performance to OFF

Co-authored-by: Frankie H <f@peering.sh>
This commit is contained in:
frankiexyz 2021-03-12 01:29:20 +08:00 committed by GitHub
parent cb5be014e8
commit ee88fcde68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 253 additions and 80 deletions

View File

@ -13,7 +13,6 @@ import click
import warnings import warnings
from math import isclose from math import isclose
from pathlib import Path from pathlib import Path
from pprint import pformat
from subprocess import getoutput, call, run, check_output, DEVNULL from subprocess import getoutput, call, run, check_output, DEVNULL
@ -26,7 +25,14 @@ warnings.filterwarnings("ignore")
SCRIPTS_DIR = Path("/usr/local/share/auto-cpufreq/scripts/") SCRIPTS_DIR = Path("/usr/local/share/auto-cpufreq/scripts/")
# from the highest performance to the lowest # from the highest performance to the lowest
ALL_GOVERNORS = ("performance", "ondemand", "conservative", "schedutil", "userspace", "powersave") ALL_GOVERNORS = (
"performance",
"ondemand",
"conservative",
"schedutil",
"userspace",
"powersave",
)
CPUS = os.cpu_count() CPUS = os.cpu_count()
# Note: # Note:
@ -34,8 +40,8 @@ CPUS = os.cpu_count()
# decraled where their execution takes place # decraled where their execution takes place
# powersave/performance system load thresholds # powersave/performance system load thresholds
powersave_load_threshold = (75*CPUS)/100 powersave_load_threshold = (75 * CPUS) / 100
performance_load_threshold = (50*CPUS)/100 performance_load_threshold = (50 * CPUS) / 100
# auto-cpufreq stats file path # auto-cpufreq stats file path
auto_cpufreq_stats_path = None auto_cpufreq_stats_path = None
@ -49,41 +55,53 @@ else:
# daemon check # daemon check
dcheck = getoutput("snapctl get daemon") dcheck = getoutput("snapctl get daemon")
def file_stats(): def file_stats():
global auto_cpufreq_stats_file global auto_cpufreq_stats_file
auto_cpufreq_stats_file = open(auto_cpufreq_stats_path, "w") auto_cpufreq_stats_file = open(auto_cpufreq_stats_path, "w")
sys.stdout = auto_cpufreq_stats_file sys.stdout = auto_cpufreq_stats_file
# get distro name # get distro name
dist_name = distro.id() dist_name = distro.id()
# display running version of auto-cpufreq # display running version of auto-cpufreq
def app_version(): def app_version():
print("auto-cpufreq version:") print("auto-cpufreq version:")
# snap package # snap package
if os.getenv('PKG_MARKER') == "SNAP": if os.getenv("PKG_MARKER") == "SNAP":
print(getoutput("echo Snap: $SNAP_VERSION")) print(getoutput("echo Snap: $SNAP_VERSION"))
# aur package # aur package
elif dist_name in ["arch", "manjaro", "garuda"]: elif dist_name in ["arch", "manjaro", "garuda"]:
aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True) aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True)
if aur_pkg_check == 1: if aur_pkg_check == 1:
print("Git commit:", check_output(["git", "describe", "--always"]).strip().decode()) print(
"Git commit:",
check_output(["git", "describe", "--always"]).strip().decode(),
)
else: else:
print(getoutput("pacman -Qi auto-cpufreq | grep Version")) print(getoutput("pacman -Qi auto-cpufreq | grep Version"))
else: else:
# source code (auto-cpufreq-installer) # source code (auto-cpufreq-installer)
try: try:
print("Git commit:", check_output(["git", "describe", "--always"]).strip().decode()) print(
except: "Git commit:",
check_output(["git", "describe", "--always"]).strip().decode(),
)
except Exception as e:
print(repr(e))
pass pass
def app_res_use(): def app_res_use():
p = psutil.Process() p = psutil.Process()
print("auto-cpufreq system resource consumption:") print("auto-cpufreq system resource consumption:")
print("cpu usage:", p.cpu_percent(), "%") print("cpu usage:", p.cpu_percent(), "%")
print("memory use:", round(p.memory_percent(),2), "%") print("memory use:", round(p.memory_percent(), 2), "%")
# set/change state of turbo # set/change state of turbo
def turbo(value: bool = None): def turbo(value: bool = None):
@ -119,7 +137,8 @@ def turbo(value: bool = None):
return value return value
# display current state of turbo
# display current state of turbo
def get_turbo(): def get_turbo():
if turbo(): if turbo():
@ -127,23 +146,24 @@ def get_turbo():
else: else:
print("Currently turbo boost is: off") print("Currently turbo boost is: off")
def charging(): def charging():
""" """
get charge state: is battery charging or discharging get charge state: is battery charging or discharging
""" """
power_dir = "/sys/class/power_supply/" power_dir = "/sys/class/power_supply/"
computer_type = getoutput('dmidecode --string chassis-type') computer_type = getoutput("dmidecode --string chassis-type")
if computer_type in [ "Notebook", "Laptop", "Convertible", "Portable" ]: if computer_type in ["Notebook", "Laptop", "Convertible", "Portable"]:
# AC adapter states: 0, 1, unknown # AC adapter states: 0, 1, unknown
ac_info = getoutput(f"grep . {power_dir}A*/online").splitlines() ac_info = getoutput(f"grep . {power_dir}A*/online").splitlines()
# if there's one ac-adapter on-line, ac_state is True # if there's one ac-adapter on-line, ac_state is True
ac_state = any(['1' in ac.split(':')[-1] for ac in ac_info]) ac_state = any(["1" in ac.split(":")[-1] for ac in ac_info])
else: else:
has_battery = psutil.sensors_battery() is not None has_battery = psutil.sensors_battery() is not None
if has_battery == True: if has_battery:
power_pluggedin = psutil.sensors_battery().power_plugged power_pluggedin = psutil.sensors_battery().power_plugged
if power_pluggedin == True: if power_pluggedin:
ac_state = True ac_state = True
else: else:
ac_state = False ac_state = False
@ -176,7 +196,12 @@ def get_avail_performance():
def get_current_gov(): def get_current_gov():
return print("Currently using:", getoutput("cpufreqctl.auto-cpufreq --governor").strip().split(" ")[0], "governor") return print(
"Currently using:",
getoutput("cpufreqctl.auto-cpufreq --governor").strip().split(" ")[0],
"governor",
)
def cpufreqctl(): def cpufreqctl():
""" """
@ -184,14 +209,18 @@ def cpufreqctl():
""" """
# detect if running on a SNAP # detect if running on a SNAP
if os.getenv('PKG_MARKER') == "SNAP": if os.getenv("PKG_MARKER") == "SNAP":
pass pass
else: else:
# deploy cpufreqctl.auto-cpufreq script # deploy cpufreqctl.auto-cpufreq script
if os.path.isfile("/usr/bin/cpufreqctl"): if os.path.isfile("/usr/bin/cpufreqctl"):
shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq") shutil.copy(
SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq"
)
else: else:
shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq") shutil.copy(
SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq"
)
def cpufreqctl_restore(): def cpufreqctl_restore():
@ -199,39 +228,53 @@ def cpufreqctl_restore():
remove cpufreqctl.auto-cpufreq script remove cpufreqctl.auto-cpufreq script
""" """
# detect if running on a SNAP # detect if running on a SNAP
if os.getenv('PKG_MARKER') == "SNAP": if os.getenv("PKG_MARKER") == "SNAP":
pass pass
else: else:
if os.path.isfile("/usr/bin/cpufreqctl.auto-cpufreq"): if os.path.isfile("/usr/bin/cpufreqctl.auto-cpufreq"):
os.remove("/usr/bin/cpufreqctl.auto-cpufreq") os.remove("/usr/bin/cpufreqctl.auto-cpufreq")
def footer(l=79): def footer(l=79):
print("\n" + "-" * l + "\n") print("\n" + "-" * l + "\n")
def daemon_not_found(): def daemon_not_found():
print("\n" + "-" * 32 + " Daemon check " + "-" * 33 + "\n") print("\n" + "-" * 32 + " Daemon check " + "-" * 33 + "\n")
print("ERROR:\n\nDaemon not enabled, must run install first, i.e: \nsudo auto-cpufreq --install") print(
"ERROR:\n\nDaemon not enabled, must run install first, i.e: \nsudo auto-cpufreq --install"
)
footer() footer()
def deploy_complete_msg(): def deploy_complete_msg():
print("\n" + "-" * 17 + " auto-cpufreq daemon installed and running " + "-" * 17 + "\n") print(
"\n"
+ "-" * 17
+ " auto-cpufreq daemon installed and running "
+ "-" * 17
+ "\n"
)
print("To view live stats, run:\nauto-cpufreq --stats") print("To view live stats, run:\nauto-cpufreq --stats")
print("\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove") print(
"\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove"
)
footer() footer()
def deprecated_log_msg(): def deprecated_log_msg():
print("\n" + "-" * 24 + " auto-cpufreq log file renamed " + "-" * 24 + "\n") print("\n" + "-" * 24 + " auto-cpufreq log file renamed " + "-" * 24 + "\n")
print("The --log flag has been renamed to --stats\n") print("The --log flag has been renamed to --stats\n")
print("To view live stats, run:\nauto-cpufreq --stats") print("To view live stats, run:\nauto-cpufreq --stats")
footer() footer()
def remove_complete_msg(): def remove_complete_msg():
print("\n" + "-" * 25 + " auto-cpufreq daemon removed " + "-" * 25 + "\n") print("\n" + "-" * 25 + " auto-cpufreq daemon removed " + "-" * 25 + "\n")
print("auto-cpufreq successfully removed.") print("auto-cpufreq successfully removed.")
footer() footer()
def deploy_daemon(): def deploy_daemon():
print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon " + "-" * 22 + "\n") print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon " + "-" * 22 + "\n")
@ -248,13 +291,15 @@ def deploy_daemon():
f.seek(0) f.seek(0)
f.truncate() f.truncate()
f.write(content.replace(orig_set, change_set)) f.write(content.replace(orig_set, change_set))
except: except Exception as e:
print("\nERROR:\nWas unable to turn off bluetooth on boot") print(f"\nERROR:\nWas unable to turn off bluetooth on boot\n{repr(e)}")
auto_cpufreq_stats_path.touch(exist_ok=True) auto_cpufreq_stats_path.touch(exist_ok=True)
print("\n* Deploy auto-cpufreq install script") print("\n* Deploy auto-cpufreq install script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/bin/auto-cpufreq-install") shutil.copy(
SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/bin/auto-cpufreq-install"
)
print("\n* Deploy auto-cpufreq remove script") print("\n* Deploy auto-cpufreq remove script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/bin/auto-cpufreq-remove") shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/bin/auto-cpufreq-remove")
@ -282,8 +327,8 @@ def remove():
f.seek(0) f.seek(0)
f.truncate() f.truncate()
f.write(content.replace(change_set, orig_set)) f.write(content.replace(change_set, orig_set))
except: except Exception as e:
print("\nERROR:\nWas unable to turn on bluetooth on boot") print(f"\nERROR:\nWas unable to turn on bluetooth on boot\n{repr(e)}")
# run auto-cpufreq daemon install script # run auto-cpufreq daemon install script
call("/usr/bin/auto-cpufreq-remove", shell=True) call("/usr/bin/auto-cpufreq-remove", shell=True)
@ -305,35 +350,47 @@ def remove():
def gov_check(): def gov_check():
for gov in get_avail_gov(): for gov in get_avail_gov():
if gov not in ALL_GOVERNORS: if gov not in ALL_GOVERNORS:
print("\n" + "-" * 18 + " Checking for necessary scaling governors " + "-" * 19 + "\n") print(
sys.exit("ERROR:\n\nCouldn't find any of the necessary scaling governors.\n") "\n"
+ "-" * 18
+ " Checking for necessary scaling governors "
+ "-" * 19
+ "\n"
)
sys.exit(
"ERROR:\n\nCouldn't find any of the necessary scaling governors.\n"
)
# root check func # root check func
def root_check(): def root_check():
if not os.geteuid() == 0: if not os.geteuid() == 0:
print("\n" + "-" * 33 + " Root check " + "-" * 34 + "\n") print("\n" + "-" * 33 + " Root check " + "-" * 34 + "\n")
print("ERROR:\n\nMust be run root for this functionality to work, i.e: \nsudo auto-cpufreq") print(
"ERROR:\n\nMust be run root for this functionality to work, i.e: \nsudo auto-cpufreq"
)
footer() footer()
exit(1) exit(1)
# refresh countdown # refresh countdown
def countdown(s): def countdown(s):
# Fix for wrong stats output and "TERM environment variable not set" # Fix for wrong stats output and "TERM environment variable not set"
os.environ['TERM'] = 'xterm' os.environ["TERM"] = "xterm"
for remaining in range(s, 0, -1): for remaining in range(s, 0, -1):
sys.stdout.write("\r") sys.stdout.write("\r")
sys.stdout.write("\t\t\t\"auto-cpufreq\" refresh in:{:2d}".format(remaining)) sys.stdout.write('\t\t\t"auto-cpufreq" refresh in:{:2d}'.format(remaining))
sys.stdout.flush() sys.stdout.flush()
time.sleep(1) time.sleep(1)
if auto_cpufreq_stats_file is not None: if auto_cpufreq_stats_file is not None:
auto_cpufreq_stats_file.seek(0) auto_cpufreq_stats_file.seek(0)
auto_cpufreq_stats_file.truncate(0) auto_cpufreq_stats_file.truncate(0)
# execution timestamp # execution timestamp
from datetime import datetime from datetime import datetime
now = datetime.now() now = datetime.now()
current_time = now.strftime("%B %d (%A) - %H:%M:%S") current_time = now.strftime("%B %d (%A) - %H:%M:%S")
print("\n\t\tExecuted on:", current_time) print("\n\t\tExecuted on:", current_time)
@ -341,6 +398,7 @@ def countdown(s):
else: else:
run("clear") run("clear")
# get cpu usage + system load for (last minute) # get cpu usage + system load for (last minute)
def display_load(): def display_load():
@ -354,13 +412,20 @@ def display_load():
print("Total system load:", load1m) print("Total system load:", load1m)
print("Average temp. of all cores:", avg_all_core_temp, "°C", "\n") print("Average temp. of all cores:", avg_all_core_temp, "°C", "\n")
# set powersave and enable turbo # set powersave and enable turbo
def set_powersave(): def set_powersave():
print(f"Setting to use: \"{get_avail_powersave()}\" governor") print(f'Setting to use: "{get_avail_powersave()}" governor')
run(f"cpufreqctl.auto-cpufreq --governor --set={get_avail_powersave()}", shell=True) run(f"cpufreqctl.auto-cpufreq --governor --set={get_avail_powersave()}", shell=True)
if Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists() and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() == False: if (
Path(
"/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference"
).exists()
and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists()
is False
):
run("cpufreqctl.auto-cpufreq --epp --set=balance_power", shell=True) run("cpufreqctl.auto-cpufreq --epp --set=balance_power", shell=True)
print("Setting to use: \"balance_power\" EPP") print('Setting to use: "balance_power" EPP')
# get CPU utilization as a percentage # get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1) cpuload = psutil.cpu_percent(interval=1)
@ -373,7 +438,9 @@ def set_powersave():
print("Average temp. of all cores:", avg_all_core_temp, "°C") print("Average temp. of all cores:", avg_all_core_temp, "°C")
# conditions for setting turbo in powersave # conditions for setting turbo in powersave
if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose(max(psutil.cpu_percent(percpu=True, interval=0.01)), 100): if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose(
max(psutil.cpu_percent(percpu=True, interval=0.01)), 100
):
print("\nHigh CPU load") print("\nHigh CPU load")
# high cpu usage trigger # high cpu usage trigger
@ -383,7 +450,13 @@ def set_powersave():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 20 and avg_all_core_temp >= 70: elif cpuload <= 20 and avg_all_core_temp >= 70:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off") print("setting turbo boost: off")
turbo(False) turbo(False)
else: else:
@ -400,7 +473,13 @@ def set_powersave():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 20 and avg_all_core_temp >= 65: elif cpuload <= 20 and avg_all_core_temp >= 65:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off") print("setting turbo boost: off")
turbo(False) turbo(False)
else: else:
@ -417,7 +496,13 @@ def set_powersave():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 20 and avg_all_core_temp >= 60: elif cpuload <= 20 and avg_all_core_temp >= 60:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off") print("setting turbo boost: off")
turbo(False) turbo(False)
else: else:
@ -440,7 +525,9 @@ def mon_powersave():
print("Total system load:", load1m) print("Total system load:", load1m)
print("Average temp. of all cores:", avg_all_core_temp, "°C") print("Average temp. of all cores:", avg_all_core_temp, "°C")
if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose(max(psutil.cpu_percent(percpu=True, interval=0.01)), 100): if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose(
max(psutil.cpu_percent(percpu=True, interval=0.01)), 100
):
print("\nHigh CPU load") print("\nHigh CPU load")
# high cpu usage trigger # high cpu usage trigger
@ -450,7 +537,13 @@ def mon_powersave():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 20 and avg_all_core_temp >= 70: elif cpuload <= 20 and avg_all_core_temp >= 70:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("suggesting to set turbo boost: off") print("suggesting to set turbo boost: off")
get_turbo() get_turbo()
else: else:
@ -467,7 +560,13 @@ def mon_powersave():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 20 and avg_all_core_temp >= 65: elif cpuload <= 20 and avg_all_core_temp >= 65:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("suggesting to set turbo boost: off") print("suggesting to set turbo boost: off")
get_turbo() get_turbo()
else: else:
@ -484,7 +583,13 @@ def mon_powersave():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 20 and avg_all_core_temp >= 60: elif cpuload <= 20 and avg_all_core_temp >= 60:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("suggesting to set turbo boost: off") print("suggesting to set turbo boost: off")
get_turbo() get_turbo()
else: else:
@ -493,14 +598,24 @@ def mon_powersave():
footer() footer()
# set performance and enable turbo # set performance and enable turbo
def set_performance(): def set_performance():
print(f"Setting to use: \"{get_avail_performance()}\" governor") print(f'Setting to use: "{get_avail_performance()}" governor')
run(f"cpufreqctl.auto-cpufreq --governor --set={get_avail_performance()}", shell=True) run(
if Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists() and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() == False: f"cpufreqctl.auto-cpufreq --governor --set={get_avail_performance()}",
shell=True,
)
if (
Path(
"/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference"
).exists()
and Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists()
is False
):
run("cpufreqctl.auto-cpufreq --epp --set=balance_performance", shell=True) run("cpufreqctl.auto-cpufreq --epp --set=balance_performance", shell=True)
print("Setting to use: \"balance_performance\" EPP") print('Setting to use: "balance_performance" EPP')
# get CPU utilization as a percentage # get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1) cpuload = psutil.cpu_percent(interval=1)
@ -512,7 +627,10 @@ def set_performance():
print("Total system load:", load1m) print("Total system load:", load1m)
print("Average temp. of all cores:", avg_all_core_temp, "°C") print("Average temp. of all cores:", avg_all_core_temp, "°C")
if psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0 or max(psutil.cpu_percent(percpu=True, interval=0.01)) >= 75: if (
psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0
or max(psutil.cpu_percent(percpu=True, interval=0.01)) >= 75
):
print("\nHigh CPU load") print("\nHigh CPU load")
# high cpu usage trigger # high cpu usage trigger
@ -522,7 +640,13 @@ def set_performance():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 25 and avg_all_core_temp >= 70: elif cpuload <= 25 and avg_all_core_temp >= 70:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off") print("setting turbo boost: off")
turbo(False) turbo(False)
else: else:
@ -539,7 +663,13 @@ def set_performance():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 25 and avg_all_core_temp >= 65: elif cpuload <= 25 and avg_all_core_temp >= 65:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off") print("setting turbo boost: off")
turbo(False) turbo(False)
else: else:
@ -556,12 +686,18 @@ def set_performance():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 25 and avg_all_core_temp >= 60: elif cpuload <= 25 and avg_all_core_temp >= 60:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off") print("setting turbo boost: off")
turbo(False) turbo(False)
else: else:
print("setting turbo boost: on") print("setting turbo boost: off")
turbo(True) turbo(False)
footer() footer()
@ -582,7 +718,10 @@ def mon_performance():
# get system/CPU load # get system/CPU load
load1m, _, _ = os.getloadavg() load1m, _, _ = os.getloadavg()
if psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0 or max(psutil.cpu_percent(percpu=True, interval=0.01)) >= 75: if (
psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0
or max(psutil.cpu_percent(percpu=True, interval=0.01)) >= 75
):
print("\nHigh CPU load") print("\nHigh CPU load")
# high cpu usage trigger # high cpu usage trigger
@ -592,7 +731,13 @@ def mon_performance():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 25 and avg_all_core_temp >= 70: elif cpuload <= 25 and avg_all_core_temp >= 70:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("suggesting to set turbo boost: off") print("suggesting to set turbo boost: off")
get_turbo() get_turbo()
else: else:
@ -609,7 +754,13 @@ def mon_performance():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 25 and avg_all_core_temp >= 65: elif cpuload <= 25 and avg_all_core_temp >= 65:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("suggesting to set turbo boost: off") print("suggesting to set turbo boost: off")
get_turbo() get_turbo()
else: else:
@ -626,7 +777,13 @@ def mon_performance():
# set turbo state based on average of all core temperatures # set turbo state based on average of all core temperatures
elif cpuload <= 25 and avg_all_core_temp >= 60: elif cpuload <= 25 and avg_all_core_temp >= 60:
print("Optimal total CPU usage:", cpuload, "%, high average core temp:", avg_all_core_temp, "°C") print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("suggesting to set turbo boost: off") print("suggesting to set turbo boost: off")
get_turbo() get_turbo()
else: else:
@ -662,25 +819,30 @@ def mon_autofreq():
if charging(): if charging():
print("Battery is: charging\n") print("Battery is: charging\n")
get_current_gov() get_current_gov()
print(f"Suggesting use of \"{get_avail_performance()}\" governor") print(f'Suggesting use of "{get_avail_performance()}" governor')
mon_performance() mon_performance()
else: else:
print("Battery is: discharging\n") print("Battery is: discharging\n")
get_current_gov() get_current_gov()
print(f"Suggesting use of \"{get_avail_powersave()}\" governor") print(f'Suggesting use of "{get_avail_powersave()}" governor')
mon_powersave() mon_powersave()
def python_info(): def python_info():
print("Python:", pl.python_version()) print("Python:", pl.python_version())
print("psutil package:", psutil.__version__) print("psutil package:", psutil.__version__)
print("platform package:", pl.__version__) print("platform package:", pl.__version__)
print("click package:", click.__version__) print("click package:", click.__version__)
# workaround: Module 'distro' has no '__version__' member () (https://github.com/nir0s/distro/issues/265) # workaround: Module 'distro' has no '__version__' member () (https://github.com/nir0s/distro/issues/265)
#print("distro:", distro.__version__) # print("distro:", distro.__version__)
run("echo \"distro package\" $(pip3 show distro | sed -n -e 's/^.*Version: //p')", shell=True) run(
"echo \"distro package\" $(pip3 show distro | sed -n -e 's/^.*Version: //p')",
shell=True,
)
def device_info(): def device_info():
print("Computer type:", getoutput('dmidecode --string chassis-type')) print("Computer type:", getoutput("dmidecode --string chassis-type"))
def distro_info(): def distro_info():
@ -692,13 +854,14 @@ def distro_info():
try: try:
with open("/var/lib/snapd/hostfs/etc/os-release", "r") as searchfile: with open("/var/lib/snapd/hostfs/etc/os-release", "r") as searchfile:
for line in searchfile: for line in searchfile:
if line.startswith('NAME='): if line.startswith("NAME="):
dist = line[5:line.find('$')].strip("\"") dist = line[5:line.find("$")].strip('"')
continue continue
elif line.startswith('VERSION='): elif line.startswith("VERSION="):
version = line[8:line.find('$')].strip("\"") version = line[8:line.find("$")].strip('"')
continue continue
except PermissionError: except PermissionError as e:
print(repr(e))
pass pass
dist = f"{dist} {version}" dist = f"{dist} {version}"
@ -710,6 +873,7 @@ def distro_info():
print("Linux distro: " + dist) print("Linux distro: " + dist)
print("Linux kernel: " + pl.release()) print("Linux kernel: " + pl.release())
def sysinfo(): def sysinfo():
""" """
get system information get system information
@ -744,13 +908,15 @@ def sysinfo():
print(f"CPU min frequency: {min_freq:.0f} MHz\n") print(f"CPU min frequency: {min_freq:.0f} MHz\n")
# get coreid's and frequencies of online cpus by parsing /proc/cpuinfo # get coreid's and frequencies of online cpus by parsing /proc/cpuinfo
coreid_info = getoutput("egrep 'processor|cpu MHz|core id' /proc/cpuinfo").split("\n") coreid_info = getoutput("egrep 'processor|cpu MHz|core id' /proc/cpuinfo").split(
"\n"
)
cpu_core = dict() cpu_core = dict()
freq_per_cpu = [] freq_per_cpu = []
for i in range(0, len(coreid_info), 3): for i in range(0, len(coreid_info), 3):
freq_per_cpu.append(float(coreid_info[i + 1].split(':')[-1])) freq_per_cpu.append(float(coreid_info[i + 1].split(":")[-1]))
cpu = int(coreid_info[i].split(':')[-1]) cpu = int(coreid_info[i].split(":")[-1])
core = int(coreid_info[i + 2].split(':')[-1]) core = int(coreid_info[i + 2].split(":")[-1])
cpu_core[cpu] = core cpu_core[cpu] = core
online_cpu_count = len(cpu_core) online_cpu_count = len(cpu_core)
@ -776,11 +942,14 @@ def sysinfo():
temp_per_cpu = [core_temp["zenpower"][0].current] * online_cpu_count temp_per_cpu = [core_temp["zenpower"][0].current] * online_cpu_count
elif "acpitz" in core_temp: elif "acpitz" in core_temp:
temp_per_cpu = [core_temp["acpitz"][0].current] * online_cpu_count temp_per_cpu = [core_temp["acpitz"][0].current] * online_cpu_count
except: except Exception as e:
print(repr(e))
pass pass
print("Core\tUsage\tTemperature\tFrequency") print("Core\tUsage\tTemperature\tFrequency")
for (cpu, usage, freq, temp) in zip(cpu_core, usage_per_cpu, freq_per_cpu, temp_per_cpu): for (cpu, usage, freq, temp) in zip(
cpu_core, usage_per_cpu, freq_per_cpu, temp_per_cpu
):
print(f"CPU{cpu}:\t{usage:>5.1f}% {temp:>3.0f} °C {freq:>5.0f} MHz") print(f"CPU{cpu}:\t{usage:>5.1f}% {temp:>3.0f} °C {freq:>5.0f} MHz")
if offline_cpus: if offline_cpus:
@ -789,7 +958,7 @@ def sysinfo():
# get average temperature of all cores # get average temperature of all cores
avg_cores_temp = sum(temp_per_cpu) avg_cores_temp = sum(temp_per_cpu)
global avg_all_core_temp global avg_all_core_temp
avg_all_core_temp = float(avg_cores_temp/online_cpu_count) avg_all_core_temp = float(avg_cores_temp / online_cpu_count)
# print current fan speed | temporarily commented # print current fan speed | temporarily commented
# current_fans = psutil.sensors_fans()['thinkpad'][0].current # current_fans = psutil.sensors_fans()['thinkpad'][0].current
@ -798,7 +967,10 @@ def sysinfo():
def no_stats_msg(): def no_stats_msg():
print("\n" + "-" * 29 + " auto-cpufreq stats " + "-" * 30 + "\n") print("\n" + "-" * 29 + " auto-cpufreq stats " + "-" * 30 + "\n")
print("ERROR: auto-cpufreq stats are missing.\n\nMake sure to run: \"auto-cpufreq --install\" first") print(
'ERROR: auto-cpufreq stats are missing.\n\nMake sure to run: "auto-cpufreq --install" first'
)
# read stats func # read stats func
def read_stats(): def read_stats():
@ -825,13 +997,14 @@ def is_running(program, argument):
for arg in proc.cmdline(): for arg in proc.cmdline():
if argument in str(arg): if argument in str(arg):
return True return True
except: except Exception as e:
print(repr(e))
continue continue
# check if auto-cpufreq --daemon is running # check if auto-cpufreq --daemon is running
def running_daemon(): def running_daemon():
if is_running('auto-cpufreq', '--daemon'): if is_running("auto-cpufreq", "--daemon"):
deploy_complete_msg() deploy_complete_msg()
exit(1) exit(1)
elif os.getenv("PKG_MARKER") == "SNAP" and dcheck == "enabled": elif os.getenv("PKG_MARKER") == "SNAP" and dcheck == "enabled":