CPUSet for Python 3

1.0.2 · active · verified Thu Apr 16

cpuset-py3 is a Python 3 compatible fork of the original cpuset library, providing functionalities to query and manipulate CPU sets (processor affinity) on Linux systems. It allows creating, modifying, and applying CPU sets to processes and threads, facilitating fine-grained control over CPU core usage. The current version is 1.0.2, and it's maintained on an as-needed basis rather than a strict release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and manipulate `CPUSet` objects. It also shows how to query the current process's affinity on Linux, with a note about the permissions often required for setting affinity.

import cpuset
import platform

print(f"Running on OS: {platform.system()}\n")

# Create a new empty cpuset
s = cpuset.CPUSet()
s.add_cpu(0)
s.add_cpu(1)
s.add_cpu(2)
print(f"Created CPUSet (0,1,2): {s.as_list()}")
print(f"As string: {s.as_str()}")
print(f"As canonical string: {s.as_canonical_str()}") # will be "0-2"
print(f"As bitmask: {hex(s.as_bitmask())}") # 0x7

# Create from a string representation
s_from_str = cpuset.CPUSet("0-3,5")
print(f"\nCPUSet from string '0-3,5': {s_from_str.as_list()}")

if platform.system() == "Linux":
    print("\nAttempting to query current process affinity (Linux-only):")
    try:
        current_affinity = cpuset.get_cpuset_for_current_process()
        print(f"  Current process affinity: {current_affinity.as_list()}")

        # Uncomment to attempt setting affinity (requires appropriate permissions):
        # print(f"  Attempting to set process affinity to {s.as_list()}...")
        # cpuset.set_cpuset_for_current_process(s)
        # updated_affinity = cpuset.get_cpuset_for_current_process()
        # print(f"  Updated process affinity: {updated_affinity.as_list()}")

    except PermissionError:
        print("  Permission denied to get/set process affinity. Try running with sudo or check capabilities.")
    except Exception as e:
        print(f"  An error occurred during system affinity call: {e}")
else:
    print("\nSystem affinity functions (get/set) are only available on Linux.")

print("\nOperations on CPUSet objects are generally platform-independent:")
s_union = s | cpuset.CPUSet("3-4")
print(f"Union (0-2 | 3-4): {s_union.as_list()}") # [0,1,2,3,4]

s_intersect = s & cpuset.CPUSet("1-3")
print(f"Intersection (0-2 & 1-3): {s_intersect.as_list()}") # [1,2]

view raw JSON →