| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
import logging |
| 22 |
|
| 23 |
import psutil |
| 24 |
|
| 25 |
from s_tui.sources.source import Source |
| 26 |
|
| 27 |
|
| 28 |
class UtilSource(Source): |
| 29 |
def __init__(self): |
| 30 |
if not hasattr(psutil, "cpu_percent") and psutil.cpu_percent(): |
| 31 |
self.is_available = False |
| 32 |
logging.debug("cpu utilization is not available from psutil") |
| 33 |
return |
| 34 |
|
| 35 |
Source.__init__(self) |
| 36 |
|
| 37 |
self.name = "Util" |
| 38 |
self.measurement_unit = "%" |
| 39 |
self.pallet = ( |
| 40 |
"util light", |
| 41 |
"util dark", |
| 42 |
"util light smooth", |
| 43 |
"util dark smooth", |
| 44 |
) |
| 45 |
|
| 46 |
total_cores = self._get_total_core_count() |
| 47 |
|
| 48 |
self.available_sensors = ["Avg"] |
| 49 |
for core_id in range(total_cores): |
| 50 |
self.available_sensors.append("Core " + str(core_id)) |
| 51 |
|
| 52 |
self.last_measurement = [0.0] * len(self.available_sensors) |
| 53 |
self.sensor_available = [True] * len(self.available_sensors) |
| 54 |
|
| 55 |
es |
| 56 |
self._cached_online_ids = self._get_online_cpu_ids() |
| 57 |
self._cached_online_len = -1 |
| 58 |
|
| 59 |
self._mark_offline_cores(total_cores, self._cached_online_ids) |
| 60 |
|
| 61 |
def update(self) -> None: |
| 62 |
try: |
| 63 |
per_cpu = psutil.cpu_percent(interval=0.0, percpu=True) |
| 64 |
except OSError: |
| 65 |
return |
| 66 |
|
| 67 |
if not per_cpu: |
| 68 |
return |
| 69 |
|
| 70 |
|
| 71 |
if len(per_cpu) != self._cached_online_len: |
| 72 |
self._cached_online_ids = self._get_online_cpu_ids() |
| 73 |
self._cached_online_len = len(per_cpu) |
| 74 |
|
| 75 |
online_ids = self._cached_online_ids |
| 76 |
|
| 77 |
if online_ids is None: |
| 78 |
ng |
| 79 |
avg = sum(per_cpu) / len(per_cpu) |
| 80 |
self.last_measurement = [avg] + [float(v) for v in per_cpu] |
| 81 |
return |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
value_by_core = dict(zip(online_ids, per_cpu)) |
| 86 |
num_cores = len(self.available_sensors) - 1 |
| 87 |
online_values = [] |
| 88 |
|
| 89 |
for core_id in range(num_cores): |
| 90 |
if core_id in value_by_core: |
| 91 |
self.last_measurement[core_id + 1] = float(value_by_core[core_id]) |
| 92 |
online_values.append(self.last_measurement[core_id + 1]) |
| 93 |
self.sensor_available[core_id + 1] = True |
| 94 |
else: |
| 95 |
self.sensor_available[core_id + 1] = False |
| 96 |
|
| 97 |
self.last_measurement[0] = ( |
| 98 |
sum(online_values) / len(online_values) if online_values else 0.0 |
| 99 |
) |
| 100 |
logging.info("Utilization recorded %s", self.last_measurement) |
| 101 |
|
| 102 |
def get_is_available(self) -> bool: |
| 103 |
return self.is_available |
| 104 |
|
| 105 |
def get_top(self) -> int: |
| 106 |
return 100 |