Skip to content

cpu

zeus.device.cpu

Abstraction layer for CPU devices.

The main function of this module is get_cpus, which returns a CPU Manager object specific to the platform.

get_current_cpu_index

get_current_cpu_index(pid='current')

Retrieves the specific CPU index (socket) where the given PID is running.

If no PID is given or pid is "current", the CPU index returned is of the CPU running the current process.

Note

Linux schedulers can preempt and reschedule processes to different CPUs. To prevent this from happening during monitoring, use taskset to pin processes to specific CPUs.

Source code in zeus/device/cpu/__init__.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def get_current_cpu_index(pid: int | Literal["current"] = "current") -> int:
    """Retrieves the specific CPU index (socket) where the given PID is running.

    If no PID is given or pid is "current", the CPU index returned is of the CPU running the current process.

    !!! Note
        Linux schedulers can preempt and reschedule processes to different CPUs. To prevent this from happening
        during monitoring, use `taskset` to pin processes to specific CPUs.
    """
    if pid == "current":
        pid = os.getpid()

    with open(f"/proc/{pid}/stat") as stat_file:
        cpu_core = int(stat_file.read().split()[38])

    with open(
        f"/sys/devices/system/cpu/cpu{cpu_core}/topology/physical_package_id"
    ) as phys_package_file:
        return int(phys_package_file.read().strip())

get_cpus

get_cpus()

Initialize and return a singleton CPU monitoring object for INTEL CPUs.

The function returns a CPU management object that aims to abstract the underlying CPU monitoring libraries (RAPL for Intel CPUs).

This function attempts to initialize CPU mointoring using RAPL. If this attempt fails, it raises a ZeusErrorInit exception.

Source code in zeus/device/cpu/__init__.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def get_cpus() -> CPUs:
    """Initialize and return a singleton CPU monitoring object for INTEL CPUs.

    The function returns a CPU management object that aims to abstract the underlying CPU monitoring libraries
    (RAPL for Intel CPUs).

    This function attempts to initialize CPU mointoring using RAPL. If this attempt fails, it raises
    a ZeusErrorInit exception.
    """
    global _cpus
    if _cpus is not None:
        return _cpus
    if rapl_is_available():
        _cpus = RAPLCPUs()
        return _cpus
    else:
        raise ZeusCPUInitError(
            "RAPL unvailable Failed to initialize CPU management library."
        )