-
-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathcore.py
1258 lines (1024 loc) · 40.5 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# auto-cpufreq - core functionality
import os
import platform as pl
import shutil
import sys
import psutil
import distro
import time
import click
import pickle
import warnings
import configparser
import pkg_resources
from math import isclose
from pathlib import Path
from shutil import which
from subprocess import getoutput, call, run, check_output, DEVNULL
# execution timestamp used in countdown func
from datetime import datetime
sys.path.append("../")
from auto_cpufreq.power_helper import *
warnings.filterwarnings("ignore")
# ToDo:
# - replace get system/CPU load from: psutil.getloadavg() | available in 5.6.2)
SCRIPTS_DIR = Path("/usr/local/share/auto-cpufreq/scripts/")
# from the highest performance to the lowest
ALL_GOVERNORS = (
"performance",
"ondemand",
"conservative",
"schedutil",
"userspace",
"powersave",
)
CPUS = os.cpu_count()
# ignore these devices under /sys/class/power_supply/
POWER_SUPPLY_IGNORELIST = ["hidpp_battery"]
# Note:
# "load1m" & "cpuload" can't be global vars and to in order to show correct data must be
# decraled where their execution takes place
# powersave/performance system load thresholds
powersave_load_threshold = (75 * CPUS) / 100
performance_load_threshold = (50 * CPUS) / 100
# auto-cpufreq stats file path
auto_cpufreq_stats_path = None
auto_cpufreq_stats_file = None
# track governor override
if os.getenv("PKG_MARKER") == "SNAP":
governor_override_state = Path("/var/snap/auto-cpufreq/current/override.pickle")
else:
governor_override_state = Path("/opt/auto-cpufreq/override.pickle")
if os.getenv("PKG_MARKER") == "SNAP":
auto_cpufreq_stats_path = Path("/var/snap/auto-cpufreq/current/auto-cpufreq.stats")
else:
auto_cpufreq_stats_path = Path("/var/run/auto-cpufreq.stats")
# daemon check
dcheck = getoutput("snapctl get daemon")
def file_stats():
global auto_cpufreq_stats_file
auto_cpufreq_stats_file = open(auto_cpufreq_stats_path, "w")
sys.stdout = auto_cpufreq_stats_file
def get_config(config_file=""):
if not hasattr(get_config, "config"):
get_config.config = configparser.ConfigParser()
if os.path.isfile(config_file):
get_config.config.read(config_file)
get_config.using_cfg_file = True
return get_config.config
def get_override():
if os.path.isfile(governor_override_state):
with open(governor_override_state, "rb") as store:
return pickle.load(store)
else:
return "default"
def set_override(override):
root_check() # Calling root_check inside if and elif might be too verbose and is susceptible to bugs in future
if override in ["powersave", "performance"]:
with open(governor_override_state, "wb") as store:
pickle.dump(override, store)
print(f"Set governor override to {override}")
elif override == "reset":
if os.path.isfile(governor_override_state):
os.remove(governor_override_state)
print("Governor override removed")
elif override is not None:
print("Invalid option.\nUse force=performance, force=powersave, or force=reset")
# get distro name
try:
dist_name = distro.id()
except PermissionError:
# Current work-around for Pop!_OS where symlink causes permission issues
print("[!] Warning: Cannot get distro name")
if os.path.exists("/etc/pop-os/os-release"):
# Check if using a Snap
if os.getenv("PKG_MARKER") == "SNAP":
print("[!] Snap install on PopOS detected, you must manually run the following"
" commands in another terminal:\n")
print("[!] Backup the /etc/os-release file:")
print("sudo mv /etc/os-release /etc/os-release-backup\n")
print("[!] Create hardlink to /etc/os-release:")
print("sudo ln /etc/pop-os/os-release /etc/os-release\n")
print("[!] Aborting. Restart auto-cpufreq when you created the hardlink")
sys.exit(1)
else:
# This should not be the case. But better be sure.
print("[!] Check /etc/os-release permissions and make sure it is not a symbolic link")
print("[!] Aborting...")
sys.exit(1)
else:
print("[!] Check /etc/os-release permissions and make sure it is not a symbolic link")
print("[!] Aborting...")
sys.exit(1)
# display running version of auto-cpufreq
def app_version():
print("auto-cpufreq version: ", end="")
# snap package
if os.getenv("PKG_MARKER") == "SNAP":
print(getoutput("echo \(Snap\) $SNAP_VERSION"))
# aur package
elif dist_name in ["arch", "manjaro", "garuda"]:
aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True)
if aur_pkg_check == 1:
print(get_formatted_version())
else:
print(getoutput("pacman -Qi auto-cpufreq | grep Version"))
else:
# source code (auto-cpufreq-installer)
try:
print(get_formatted_version())
except Exception as e:
print(repr(e))
pass
# return formatted version for a better readability
def get_formatted_version():
literal_version = pkg_resources.require("auto-cpufreq")[0].version
splitted_version = literal_version.split("+")
formatted_version = splitted_version[0]
if len(splitted_version) > 1:
formatted_version += " (git: " + splitted_version[1] + ")"
return formatted_version
def app_res_use():
p = psutil.Process()
print("auto-cpufreq system resource consumption:")
print("cpu usage:", p.cpu_percent(), "%")
print("memory use:", round(p.memory_percent(), 2), "%")
# set/change state of turbo
def turbo(value: bool = None):
"""
Get and set turbo mode
"""
p_state = Path("/sys/devices/system/cpu/intel_pstate/no_turbo")
cpufreq = Path("/sys/devices/system/cpu/cpufreq/boost")
if p_state.exists():
inverse = True
f = p_state
elif cpufreq.exists():
f = cpufreq
inverse = False
else:
print("Warning: CPU turbo is not available")
return False
if value is not None:
if inverse:
value = not value
try:
f.write_text(str(int(value)) + "\n")
except PermissionError:
print("Warning: Changing CPU turbo is not supported. Skipping.")
return False
value = bool(int(f.read_text().strip()))
if inverse:
value = not value
return value
# display current state of turbo
def get_turbo():
if turbo():
print("Currently turbo boost is: on")
else:
print("Currently turbo boost is: off")
def charging():
"""
get charge state: is battery charging or discharging
"""
power_supply_path = "/sys/class/power_supply/"
power_supplies = os.listdir(Path(power_supply_path))
# sort it so AC is 'always' first
power_supplies = sorted(power_supplies)
# check if we found power supplies. on a desktop these are not found
# and we assume we are on a powercable.
if len(power_supplies) == 0:
# nothing found found, so nothing to check
return True
# we found some power supplies, lets check their state
else:
for supply in power_supplies:
# Check if supply is in ignore list
ignore_supply = any(item in supply for item in POWER_SUPPLY_IGNORELIST)
# If found in ignore list, skip it.
if ignore_supply:
continue
try:
with open(Path(power_supply_path + supply + "/type")) as f:
supply_type = f.read()[:-1]
if supply_type == "Mains":
# we found an AC
try:
with open(Path(power_supply_path + supply + "/online")) as f:
val = int(f.read()[:-1])
if val == 1:
# we are definitely charging
return True
except FileNotFoundError:
# we could not find online, check next item
continue
elif supply_type == "Battery":
# we found a battery, check if its being discharged
try:
with open(Path(power_supply_path + supply + "/status")) as f:
val = str(f.read()[:-1])
if val == "Discharging":
# we found a discharging battery
return False
except FileNotFoundError:
# could not find status, check the next item
continue
else:
# continue to next item because current is not
# "Mains" or "Battery"
continue
except FileNotFoundError:
# could not find type, check the next item
continue
# we cannot determine discharging state, assume we are on powercable
return True
def get_avail_gov():
f = Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors")
return f.read_text().strip().split(" ")
def get_avail_powersave():
"""
Iterate over ALL_GOVERNORS in reverse order: from powersave to performance
:return:
"""
for g in ALL_GOVERNORS[::-1]:
if g in get_avail_gov():
return g
def get_avail_performance():
for g in ALL_GOVERNORS:
if g in get_avail_gov():
return g
def get_current_gov():
return print(
"Currently using:",
getoutput("cpufreqctl.auto-cpufreq --governor").strip().split(" ")[0],
"governor",
)
def cpufreqctl():
"""
deploy cpufreqctl script
"""
# detect if running on a SNAP
if os.getenv("PKG_MARKER") == "SNAP":
pass
else:
# deploy cpufreqctl.auto-cpufreq script
if not os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"):
shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/local/bin/cpufreqctl.auto-cpufreq")
def cpufreqctl_restore():
"""
remove cpufreqctl.auto-cpufreq script
"""
# detect if running on a SNAP
if os.getenv("PKG_MARKER") == "SNAP":
pass
else:
if os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"):
os.remove("/usr/local/bin/cpufreqctl.auto-cpufreq")
def footer(l=79):
print("\n" + "-" * l + "\n")
def deploy_complete_msg():
print("\n" + "-" * 17 + " auto-cpufreq daemon installed and running " + "-" * 17 + "\n")
print("To view live stats, run:\nauto-cpufreq --stats")
print("\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove")
footer()
def deprecated_log_msg():
print("\n" + "-" * 24 + " auto-cpufreq log file renamed " + "-" * 24 + "\n")
print("The --log flag has been renamed to --stats\n")
print("To view live stats, run:\nauto-cpufreq --stats")
footer()
def remove_complete_msg():
print("\n" + "-" * 25 + " auto-cpufreq daemon removed " + "-" * 25 + "\n")
print("auto-cpufreq successfully removed.")
footer()
def deploy_daemon():
print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon " + "-" * 22 + "\n")
# deploy cpufreqctl script func call
cpufreqctl()
# turn off bluetooth on boot
bluetooth_disable()
auto_cpufreq_stats_path.touch(exist_ok=True)
print("\n* Deploy auto-cpufreq install script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install")
print("\n* Deploy auto-cpufreq remove script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove")
# output warning if gnome power profile is running
gnome_power_detect_install()
gnome_power_svc_disable()
# output warning if TLP service is detected
tlp_service_detect()
call("/usr/local/bin/auto-cpufreq-install", shell=True)
def deploy_daemon_performance():
print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon (performance) " + "-" * 22 + "\n")
# check that performance is in scaling_available_governors
with open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors") as available_governors:
if "performance" not in available_governors.read():
print("\"performance\" governor is unavailable on this system, run:\n"
"sudo sudo auto-cpufreq --install\n\n"
"to install auto-cpufreq using default \"balanced\" governor.\n")
# deploy cpufreqctl script func call
cpufreqctl()
# turn off bluetooth on boot
bluetooth_disable()
auto_cpufreq_stats_path.touch(exist_ok=True)
print("\n* Deploy auto-cpufreq install script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install")
print("\n* Deploy auto-cpufreq remove script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove")
# output warning if gnome power profile is running
gnome_power_detect_install()
gnome_power_svc_disable_performance()
# output warning if TLP service is detected
tlp_service_detect()
call("/usr/local/bin/auto-cpufreq-install", shell=True)
# remove auto-cpufreq daemon
def remove_daemon():
# check if auto-cpufreq is installed
if not os.path.exists("/usr/local/bin/auto-cpufreq-remove"):
print("\nauto-cpufreq daemon is not installed.\n")
sys.exit(1)
print("\n" + "-" * 21 + " Removing auto-cpufreq daemon " + "-" * 22 + "\n")
# turn on bluetooth on boot
bluetooth_enable()
# output warning if gnome power profile is stopped
gnome_power_rm_reminder()
gnome_power_svc_enable()
# run auto-cpufreq daemon remove script
call("/usr/local/bin/auto-cpufreq-remove", shell=True)
# remove auto-cpufreq-remove
os.remove("/usr/local/bin/auto-cpufreq-remove")
# delete override pickle if it exists
if os.path.exists(governor_override_state):
os.remove(governor_override_state)
# delete stats file
if auto_cpufreq_stats_path.exists():
if auto_cpufreq_stats_file is not None:
auto_cpufreq_stats_file.close()
auto_cpufreq_stats_path.unlink()
# restore original cpufrectl script
cpufreqctl_restore()
def gov_check():
for gov in get_avail_gov():
if gov not in ALL_GOVERNORS:
print("\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
def root_check():
if not os.geteuid() == 0:
print("\n" + "-" * 33 + " Root check " + "-" * 34 + "\n")
print("ERROR:\n\nMust be run root for this functionality to work, i.e: \nsudo " + app_name)
footer()
exit(1)
# refresh countdown
def countdown(s):
# Fix for wrong stats output and "TERM environment variable not set"
os.environ["TERM"] = "xterm"
print("\t\t\"auto-cpufreq\" is about to refresh ", end = "")
# empty log file if size is larger then 10mb
if auto_cpufreq_stats_file is not None:
log_size = os.path.getsize(auto_cpufreq_stats_path)
if log_size >= 1e+7:
auto_cpufreq_stats_file.seek(0)
auto_cpufreq_stats_file.truncate(0)
# auto-refresh counter
for remaining in range(s, -1, -1):
if remaining <= 3 and remaining >= 0:
print(".", end="", flush=True)
time.sleep(0.75)
now = datetime.now()
current_time = now.strftime("%B %d (%A) - %H:%M:%S")
print("\n\t\tExecuted on:", current_time)
# get cpu usage + system load for (last minute)
def display_load():
# get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1)
# get system/CPU load
load1m, _, _ = os.getloadavg()
print("\nTotal CPU usage:", cpuload, "%")
print("Total system load: {:.2f}".format(load1m))
print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp))
# get system load average 1m, 5m, 15m (equivalent to uptime)
def display_system_load_avg():
load1m, load5m, load15m = os.getloadavg()
print(f" (load average: {load1m:.2f}, {load5m:.2f}, {load15m:.2f})")
# set minimum and maximum CPU frequencies
def set_frequencies():
"""
Sets frequencies:
- if option is used in auto-cpufreq.conf: use configured value
- if option is disabled/no conf file used: set default frequencies
Frequency setting is performed only once on power supply change
"""
power_supply = "charger" if charging() else "battery"
# don't do anything if the power supply hasn't changed
if (
hasattr(set_frequencies, "prev_power_supply")
and power_supply == set_frequencies.prev_power_supply
):
return
else:
set_frequencies.prev_power_supply = power_supply
frequency = {
"scaling_max_freq": {
"cmdargs": "--frequency-max",
"minmax": "maximum",
},
"scaling_min_freq": {
"cmdargs": "--frequency-min",
"minmax": "minimum",
},
}
if not hasattr(set_frequencies, "max_limit"):
set_frequencies.max_limit = int(getoutput(f"cpufreqctl.auto-cpufreq --frequency-max-limit"))
if not hasattr(set_frequencies, "min_limit"):
set_frequencies.min_limit = int(getoutput(f"cpufreqctl.auto-cpufreq --frequency-min-limit"))
conf = get_config()
for freq_type in frequency.keys():
value = None
if not conf.has_option(power_supply, freq_type):
# fetch and use default frequencies
if freq_type == "scaling_max_freq":
curr_freq = int(getoutput(f"cpufreqctl.auto-cpufreq --frequency-max"))
value = set_frequencies.max_limit
else:
curr_freq = int(getoutput(f"cpufreqctl.auto-cpufreq --frequency-min"))
value = set_frequencies.min_limit
if curr_freq == value:
continue
try:
frequency[freq_type]["value"] = (
value if value else int(conf[power_supply][freq_type].strip())
)
except ValueError:
print(f"Invalid value for '{freq_type}': {frequency[freq_type]['value']}")
exit(1)
if not (
set_frequencies.min_limit <= frequency[freq_type]["value"] <= set_frequencies.max_limit
):
print(
f"Given value for '{freq_type}' is not within the allowed frequencies {set_frequencies.min_limit}-{set_frequencies.max_limit} kHz"
)
exit(1)
args = f"{frequency[freq_type]['cmdargs']} --set={frequency[freq_type]['value']}"
message = f'Setting {frequency[freq_type]["minmax"]} CPU frequency to {round(frequency[freq_type]["value"]/1000)} Mhz'
# set the frequency
print(message)
run(f"cpufreqctl.auto-cpufreq {args}", shell=True)
# set powersave and enable turbo
def set_powersave():
conf = get_config()
if conf.has_option("battery", "governor"):
gov = conf["battery"]["governor"]
else:
gov = get_avail_powersave()
print(f'Setting to use: "{gov}" governor')
if get_override() != "default":
print("Warning: governor overwritten using `--force` flag.")
run(f"cpufreqctl.auto-cpufreq --governor --set={gov}", 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_power", shell=True)
print('Setting to use: "balance_power" EPP')
# set frequencies
set_frequencies()
# get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1)
# get system/CPU load
load1m, _, _ = os.getloadavg()
print("\nTotal CPU usage:", cpuload, "%")
print("Total system load: {:.2f}".format(load1m))
print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp))
# conditions for setting turbo in powersave
if conf.has_option("battery", "turbo"):
auto = conf["battery"]["turbo"]
else:
auto = "auto"
if auto == "always":
print("Configuration file enforces turbo boost")
print("setting turbo boost: on")
turbo(True)
elif auto == "never":
print("Configuration file disables turbo boost")
print("setting turbo boost: off")
turbo(False)
else:
if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose(
max(psutil.cpu_percent(percpu=True, interval=0.01)), 100
):
print("High CPU load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("setting turbo boost: on")
turbo(True)
# set turbo state based on average of all core temperatures
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("setting turbo boost: off")
turbo(False)
else:
print("setting turbo boost: off")
turbo(False)
elif load1m > powersave_load_threshold:
print("High system load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("setting turbo boost: on")
turbo(True)
# set turbo state based on average of all core temperatures
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("setting turbo boost: off")
turbo(False)
else:
print("setting turbo boost: off")
turbo(False)
else:
print("Load optimal", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("setting turbo boost: on")
turbo(True)
# set turbo state based on average of all core temperatures
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("setting turbo boost: off")
turbo(False)
else:
print("setting turbo boost: off")
turbo(False)
footer()
# make turbo suggestions in powersave
def mon_powersave():
# get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1)
# get system/CPU load
load1m, _, _ = os.getloadavg()
print("\nTotal CPU usage:", cpuload, "%")
print("Total system load: {:.2f}".format(load1m))
print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp))
if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose(
max(psutil.cpu_percent(percpu=True, interval=0.01)), 100
):
print("High CPU load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("suggesting to set turbo boost: on")
get_turbo()
# set turbo state based on average of all core temperatures
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("suggesting to set turbo boost: off")
get_turbo()
else:
print("suggesting to set turbo boost: off")
get_turbo()
elif load1m > powersave_load_threshold:
print("High system load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("suggesting to set turbo boost: on")
get_turbo()
# set turbo state based on average of all core temperatures
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("suggesting to set turbo boost: off")
get_turbo()
else:
print("suggesting to set turbo boost: off")
get_turbo()
else:
print("Load optimal", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("suggesting to set turbo boost: on")
get_turbo()
# set turbo state based on average of all core temperatures
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("suggesting to set turbo boost: off")
get_turbo()
else:
print("suggesting to set turbo boost: off")
get_turbo()
footer()
# set performance and enable turbo
def set_performance():
conf = get_config()
if conf.has_option("charger", "governor"):
gov = conf["charger"]["governor"]
else:
gov = get_avail_performance()
print(f'Setting to use: "{gov}" governor')
if get_override() != "default":
print("Warning: governor overwritten using `--force` flag.")
run(
f"cpufreqctl.auto-cpufreq --governor --set={gov}",
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)
print('Setting to use: "balance_performance" EPP')
# set frequencies
set_frequencies()
# get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1)
# get system/CPU load
load1m, _, _ = os.getloadavg()
print("\nTotal CPU usage:", cpuload, "%")
print("Total system load: {:.2f}".format(load1m))
print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp))
if conf.has_option("charger", "turbo"):
auto = conf["charger"]["turbo"]
else:
auto = "auto"
if auto == "always":
print("Configuration file enforces turbo boost")
print("setting turbo boost: on")
turbo(True)
elif auto == "never":
print("Configuration file disables turbo boost")
print("setting turbo boost: off")
turbo(False)
else:
if (
psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0
or max(psutil.cpu_percent(percpu=True, interval=0.01)) >= 75
):
print("High CPU load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("setting turbo boost: on")
turbo(True)
# set turbo state based on average of all core temperatures
elif avg_all_core_temp >= 70:
print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off")
turbo(False)
else:
print("setting turbo boost: on")
turbo(True)
elif load1m >= performance_load_threshold:
print("High system load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("setting turbo boost: on")
turbo(True)
# set turbo state based on average of all core temperatures
elif avg_all_core_temp >= 65:
print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off")
turbo(False)
else:
print("setting turbo boost: on")
turbo(True)
else:
print("Load optimal", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("setting turbo boost: on")
turbo(True)
# set turbo state based on average of all core temperatures
elif avg_all_core_temp >= 60:
print(
"Optimal total CPU usage:",
cpuload,
"%, high average core temp:",
avg_all_core_temp,
"°C",
)
print("setting turbo boost: off")
turbo(False)
else:
print("setting turbo boost: off")
turbo(False)
footer()
# make turbo suggestions in performance
def mon_performance():
# get CPU utilization as a percentage
cpuload = psutil.cpu_percent(interval=1)
# get system/CPU load
load1m, _, _ = os.getloadavg()
print("\nTotal CPU usage:", cpuload, "%")
print("Total system load: {:.2f}".format(load1m))
print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp))
# get system/CPU load
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
):
print("High CPU load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("suggesting to set turbo boost: on")
get_turbo()
# set turbo state based on average of all core temperatures
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("suggesting to set turbo boost: off")
get_turbo()
else:
print("suggesting to set turbo boost: on")
get_turbo()
elif load1m > performance_load_threshold:
print("High system load", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("suggesting to set turbo boost: on")
get_turbo()
# set turbo state based on average of all core temperatures
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("suggesting to set turbo boost: off")
get_turbo()
else:
print("suggesting to set turbo boost: on")
get_turbo()
else:
print("Load optimal", end=""), display_system_load_avg()
# high cpu usage trigger
if cpuload >= 20:
print("suggesting to set turbo boost: on")
get_turbo()