-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
core.py
814 lines (646 loc) · 26.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
#!/usr/bin/env python3
#
# auto-cpufreq - core functionality
import os
import platform as pl
import re
import shutil
import sys
import time
import warnings
from math import isclose
from pathlib import Path
from pprint import pformat
from subprocess import getoutput, call, run, check_output, DEVNULL
import psutil
import distro
import click
warnings.filterwarnings("ignore")
# ToDo:
# - re-enable CPU fan speed display and make more generic and not only for thinkpad
# - 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()
# 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 log file path
auto_cpufreq_log_path = None
auto_cpufreq_log_file = None
if os.getenv("PKG_MARKER") == "SNAP":
auto_cpufreq_log_path = Path("/var/snap/auto-cpufreq/current/auto-cpufreq.log")
else:
auto_cpufreq_log_path = Path("/var/log/auto-cpufreq.log")
# daemon check
dcheck = getoutput("snapctl get daemon")
def file_logging():
global auto_cpufreq_log_file
auto_cpufreq_log_file = open(auto_cpufreq_log_path, "w")
sys.stdout = auto_cpufreq_log_file
# ToDo: read version from snap/snapcraft.yaml and write to $SNAP/version for use with snap installs
# also come up with same kind of solution for AUR
def app_version():
try:
print("Build git commit:", check_output(["git", "describe", "--always"]).strip().decode())
except:
pass
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_dir = "/sys/class/power_supply/"
computer_type = getoutput('hostnamectl status | grep Chassis | cut -f2 -d \":\" | tr -d \' \'')
if computer_type == "laptop":
# AC adapter states: 0, 1, unknown
ac_info = getoutput(f"grep . {power_dir}A*/online").splitlines()
# 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])
else:
# if desktop ac_state is true
ac_state = True
# Possible values: Charging, Discharging, Unknown
battery_info = getoutput(f"grep . {power_dir}BAT*/status")
# need to explicitly check for each state in this order
# considering multiple batteries
if "Discharging" in battery_info:
battery_state = False
elif "Charging" in battery_info:
battery_state = True
else:
battery_state = None
# if both ac-adapter and battery states are unknown default to not charging
return ac_state or battery_state
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 os.path.isfile("/usr/bin/cpufreqctl"):
shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/bin/cpufreqctl.auto-cpufreq")
else:
shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/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/bin/cpufreqctl.auto-cpufreq"):
os.remove("/usr/bin/cpufreqctl.auto-cpufreq")
def footer(l=79):
print("\n" + "-" * l + "\n")
def daemon_not_found():
print("\n" + "-" * 32 + " Daemon check " + "-" * 33 + "\n")
print("ERROR:\n\nDaemon not enabled, must run install first, i.e: \nsudo auto-cpufreq --install")
footer()
def deploy_complete_msg():
print("\n" + "-" * 17 + " auto-cpufreq daemon installed and running " + "-" * 17 + "\n")
print("To view live log, run:\nauto-cpufreq --log")
print("\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove")
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()
print("* Turn off bluetooth on boot")
btconf = Path("/etc/bluetooth/main.conf")
try:
orig_set = "AutoEnable=true"
change_set = "AutoEnable=false"
with btconf.open(mode="r+") as f:
content = f.read()
f.seek(0)
f.truncate()
f.write(content.replace(orig_set, change_set))
except:
print("\nERROR:\nWas unable to turn off bluetooth on boot")
auto_cpufreq_log_path.touch(exist_ok=True)
print("\n* Deploy auto-cpufreq install script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/bin/auto-cpufreq-install")
print("\n* Deploy auto-cpufreq remove script")
shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/bin/auto-cpufreq-remove")
call("/usr/bin/auto-cpufreq-install", shell=True)
# remove auto-cpufreq daemon
def remove():
# check if auto-cpufreq is installed
if not os.path.exists("/usr/bin/auto-cpufreq-remove"):
print("\nauto-cpufreq daemon is not installed.\n")
sys.exit(1)
print("\n" + "-" * 21 + " Removing auto-cpufreq daemon " + "-" * 22 + "\n")
print("* Turn on bluetooth on boot")
btconf = "/etc/bluetooth/main.conf"
try:
orig_set = "AutoEnable=true"
change_set = "AutoEnable=false"
with open(btconf, "r+") as f:
content = f.read()
f.seek(0)
f.truncate()
f.write(content.replace(change_set, orig_set))
except:
print("\nERROR:\nWas unable to turn on bluetooth on boot")
# run auto-cpufreq daemon install script
call("/usr/bin/auto-cpufreq-remove", shell=True)
# remove auto-cpufreq-remove
os.remove("/usr/bin/auto-cpufreq-remove")
# delete log file
if auto_cpufreq_log_path.exists():
if auto_cpufreq_log_file is not None:
auto_cpufreq_log_file.close()
auto_cpufreq_log_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 auto-cpufreq")
footer()
exit(1)
# refresh countdown
def countdown(s):
# Fix for wrong log output and "TERM environment variable not set"
os.environ['TERM'] = 'xterm'
for remaining in range(s, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("\t\t\t\"auto-cpufreq\" refresh in:{:2d}".format(remaining))
sys.stdout.flush()
time.sleep(1)
if auto_cpufreq_log_file is not None:
auto_cpufreq_log_file.seek(0)
auto_cpufreq_log_file.truncate(0)
else:
run("clear")
# 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:", load1m)
print("Average temp. of all cores:", avg_all_core_temp, "°C", "\n")
# set powersave and enable turbo
def set_powersave():
print(f"Setting to use: \"{get_avail_powersave()}\" governor")
run(f"cpufreqctl.auto-cpufreq --governor --set={get_avail_powersave()}", shell=True)
if Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists():
run("cpufreqctl.auto-cpufreq --epp --set=balance_power", shell=True)
print("Setting to use: \"balance_power\" EPP")
# 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:", load1m)
print("Average temp. of all cores:", avg_all_core_temp, "°C")
# 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):
print("\nHigh CPU load")
# 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("\nHigh system load")
# 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("\nLoad optimal")
# 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:", load1m)
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):
print("\nHigh CPU load")
# 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("\nHigh system load")
# 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("\nLoad optimal")
# 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():
print(f"Setting to use: \"{get_avail_performance()}\" governor")
run(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() == False:
run("cpufreqctl.auto-cpufreq --epp --set=balance_performance", shell=True)
print("Setting to use: \"balance_performance\" EPP")
# 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:", load1m)
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:
print("\nHigh CPU load")
# 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 <= 25 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: on")
turbo(True)
elif load1m >= performance_load_threshold:
print("\nHigh system load")
# 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 <= 25 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: on")
turbo(True)
else:
print("\nLoad optimal")
# 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 <= 25 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: on")
turbo(True)
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:", load1m)
print("Average temp. of all cores:", avg_all_core_temp, "°C")
# 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("\nHigh CPU load")
# 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("\nHigh system load")
# 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("\nLoad optimal")
# 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 >= 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: on")
get_turbo()
footer()
def set_autofreq():
"""
set cpufreq governor based if device is charging
"""
print("\n" + "-" * 28 + " CPU frequency scaling " + "-" * 28 + "\n")
# determine which governor should be used
if charging():
print("Battery is: charging\n")
set_performance()
else:
print("Battery is: discharging\n")
set_powersave()
def mon_autofreq():
"""
make cpufreq suggestions
:return:
"""
print("\n" + "-" * 28 + " CPU frequency scaling " + "-" * 28 + "\n")
# determine which governor should be used
if charging():
print("Battery is: charging\n")
get_current_gov()
print(f"Suggesting use of \"{get_avail_performance()}\" governor")
mon_performance()
else:
print("Battery is: discharging\n")
get_current_gov()
print(f"Suggesting use of \"{get_avail_powersave()}\" governor")
mon_powersave()
def python_info():
print("Python:", pl.python_version())
print("psutil package:", psutil.__version__)
print("platform package:", pl.__version__)
print("click package:", click.__version__)
# workaround: Module 'distro' has no '__version__' member () (https://github.com/nir0s/distro/issues/265)
#print("distro:", distro.__version__)
run("echo \"distro package\" $(pip3 show distro | sed -n -e 's/^.*Version: //p')", shell=True)
def distro_info():
dist = "UNKNOWN distro"
version = "UNKNOWN version"
# get distro information in snap env.
if os.getenv("PKG_MARKER") == "SNAP":
try:
with open("/var/lib/snapd/hostfs/etc/os-release", "r") as searchfile:
for line in searchfile:
if line.startswith('NAME='):
dist = line[5:line.find('$')].strip("\"")
continue
elif line.startswith('VERSION='):
version = line[8:line.find('$')].strip("\"")
continue
except PermissionError:
pass
dist = f"{dist} {version}"
else:
# get distro information
fdist = distro.linux_distribution()
dist = " ".join(x for x in fdist)
print("Linux distro: " + dist)
print("Linux kernel: " + pl.release())
def sysinfo():
"""
get system information
"""
# processor_info
model_name = getoutput("egrep 'model name' /proc/cpuinfo -m 1").split(":")[-1]
print(f"Processor:{model_name}")
# get core count
total_cpu_count = int(getoutput("nproc --all"))
print("Cores:", total_cpu_count)
# get architecture
cpu_arch = pl.machine()
print("Architecture:", cpu_arch)
# get driver
driver = getoutput("cpufreqctl.auto-cpufreq --driver")
print("Driver: " + driver)
# get usage and freq info of cpus
usage_per_cpu = psutil.cpu_percent(interval=1, percpu=True)
# psutil current freq not used, gives wrong values with offline cpu's
minmax_freq_per_cpu = psutil.cpu_freq(percpu=True)
# max and min freqs, psutil reports wrong max/min freqs whith offline cores with percpu=False
max_freq = max([freq.max for freq in minmax_freq_per_cpu])
min_freq = min([freq.min for freq in minmax_freq_per_cpu])
print("\n" + "-" * 30 + " Current CPU states " + "-" * 30 + "\n")
print(f"CPU max frequency: {max_freq:.0f} MHz")
print(f"CPU min frequency: {min_freq:.0f} MHz\n")
# 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")
cpu_core = dict()
freq_per_cpu = []
for i in range(0, len(coreid_info), 3):
freq_per_cpu.append(float(coreid_info[i + 1].split(':')[-1]))
cpu = int(coreid_info[i].split(':')[-1])
core = int(coreid_info[i + 2].split(':')[-1])
cpu_core[cpu] = core
online_cpu_count = len(cpu_core)
offline_cpus = [str(cpu) for cpu in range(total_cpu_count) if cpu not in cpu_core]
# temperatures
core_temp = psutil.sensors_temperatures()
temp_per_cpu = [float("nan")] * online_cpu_count
try:
if "coretemp" in core_temp:
# list labels in 'coretemp'
core_temp_labels = [temp.label for temp in core_temp["coretemp"]]
for i, cpu in enumerate(cpu_core):
# get correct index in core_temp
core = cpu_core[cpu]
cpu_temp_index = core_temp_labels.index(f"Core {core}")
temp_per_cpu[i] = core_temp["coretemp"][cpu_temp_index].current
elif "k10temp" in core_temp:
# https://www.kernel.org/doc/Documentation/hwmon/k10temp
temp_per_cpu = [core_temp["k10temp"][0].current] * online_cpu_count
elif "zenpower" in core_temp:
# https://github.com/AdnanHodzic/auto-cpufreq/issues/145#issuecomment-763294009
temp_per_cpu = [core_temp["zenpower"][0].current] * online_cpu_count
elif "acpitz" in core_temp:
temp_per_cpu = [core_temp["acpitz"][0].current] * online_cpu_count
except:
pass
print("\t Usage Temperature Frequency")
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")
if offline_cpus:
print(f"\nDisabled CPUs: {','.join(offline_cpus)}")
# get average temperature of all cores
avg_cores_temp = sum(temp_per_cpu)
global avg_all_core_temp
avg_all_core_temp = float(avg_cores_temp/online_cpu_count)
# print current fan speed | temporarily commented
# current_fans = psutil.sensors_fans()['thinkpad'][0].current
# print("\nCPU fan speed:", current_fans, "RPM")
def no_log_msg():
print("\n" + "-" * 30 + " auto-cpufreq log " + "-" * 31 + "\n")
print("ERROR: auto-cpufreq log is missing.\n\nMake sure to run: \"auto-cpufreq --install\" first")
# read log func
def read_log():
# readlog
if os.path.isfile(auto_cpufreq_log_path):
call(["tail", "-n 50", "-f", str(auto_cpufreq_log_path)], stderr=DEVNULL)
else:
no_log_msg()
footer()
# check if program (argument) is running
def is_running(program, argument):
# iterate over all process id's found by psutil
for pid in psutil.pids():
try:
# requests the process information corresponding to each process id
proc = psutil.Process(pid)
# check if value of program-variable that was used to call the function
# matches the name field of the plutil.Process(pid) output
if program in proc.name():
# check output of p.name(), output name of program
# p.cmdline() - echo the exact command line via which p was called.
for arg in proc.cmdline():
if argument in str(arg):
return True
except:
continue
# check if auto-cpufreq --daemon is running
def running_daemon():
if is_running('auto-cpufreq', '--daemon'):
deploy_complete_msg()
exit(1)
elif os.getenv("PKG_MARKER") == "SNAP" and dcheck == "enabled":
deploy_complete_msg()
exit(1)