Intel® Distribution for Python*
Engage in discussions with community peers related to Python* applications and core computational packages.
446 Discussions

I use Python to enable load balancing for the 14th generation.

俊明
Beginner
2,970 Views

I use the i7-14700F to achieve smooth performance without stuttering and reduce heat generation. Through affinity, I optimize the efficiency of idle cores, maximizing CPU performance while reducing heat. Will Intel consider this for future updates?

2025-02-25 17 10 19.png

Needs to be run as administrator.


import psutil
import time
import threading

class CPUMonitor:
def __init__(self):
self.running = threading.Event()
self.thread = None
self.monitor_interval = 0 # Set monitoring interval to 0
self.load_threshold = 30 # Load threshold
total_cores = psutil.cpu_count(logical=False)
self.min_cores = total_cores - 3
self.disabled_cores = set()
self.kept_cores = set()
self.start()

def get_cpu_load(self):
return psutil.cpu_percent(percpu=True)

def set_cpu_affinity(self, cpu_indices):
success_count = 0
fail_count = 0

# Directly handle the objects in the process iterator to avoid secondary queries
for proc in psutil.process_iter(attrs=['pid', 'name']):
if proc.info['name'].lower() in ['system', 'idle']:
continue
try:
proc.cpu_affinity(cpu_indices)
success_count += 1
except (psutil.NoSuchProcess, psutil.AccessDenied):
fail_count += 1
except Exception as e:
print(f"Unknown error occurred while setting process {proc.info['pid']}: {e}")
fail_count += 1

return f"Successfully set {success_count} processes | Failed {fail_count} processes", True

def monitor_and_set_affinity(self):
while self.running.is_set():
cpu_loads = self.get_cpu_load()
always_on_cores = list(self.kept_cores)
available_indices = [i for i in range(len(cpu_loads)) if i not in self.disabled_cores]

sorted_cores = sorted(available_indices, key=lambda i: cpu_loads[i])
selected_cores = always_on_cores.copy()
remaining_cores = [i for i in sorted_cores if i not in always_on_cores]

while len(selected_cores) < self.min_cores and remaining_cores:
selected_cores.append(remaining_cores.pop(0))

additional_cores = [i for i in remaining_cores if cpu_loads[i] < self.load_threshold]
selected_cores.extend(additional_cores)

if selected_cores:
result_msg, has_processed = self.set_cpu_affinity(selected_cores)
print(f"Available cores: {selected_cores}\n{result_msg}")
else:
print(f"Unable to meet the minimum core count of {self.min_cores}")

self.display_cpu_load(cpu_loads)
if self.monitor_interval > 0:
time.sleep(self.monitor_interval)

def display_cpu_load(self, cpu_loads):
print("\nCurrent CPU core load status:")
for i, load in enumerate(cpu_loads):
status = "Disabled" if i in self.disabled_cores else "Always on" if i in self.kept_cores else "Dynamic"
print(f"Core {i}: {load:.1f}% ({status})")

def start(self):
if not self.running.is_set():
self.running.set()
self.thread = threading.Thread(target=self.monitor_and_set_affinity, daemon=True)
self.thread.start()
print("Monitoring started")
else:
print("Monitoring is already running")

def stop(self):
if self.running.is_set():
self.running.clear()
print("Monitoring stopped")
else:
print("Monitoring has not been started")

def main():
monitor = CPUMonitor()
while True:
print("\n=== CPU Core Management Tool ===")
print("1. Stop monitoring")
print("2. Exit")

choice = input("Please enter an option (1-2): ")

if choice == '1':
monitor.stop()
elif choice == '2':
monitor.stop()
print("Program exited")
break
else:
print("Invalid option, please try again")

if __name__ == "__main__":
main()

0 Kudos
2 Replies
StefR_Intel
Moderator
2,886 Views

Thank you for sharing your insights and your approach to optimizing CPU performance. We appreciate your interest in enhancing our product. At this time, our focus is on maintaining the current scope and features of our product. However, we will keep your feedback in mind as we continue to evaluate potential updates and improvements. Please feel free to reach out with any other ideas or questions you may have.

 

Regards,

Stef

0 Kudos
俊明
Beginner
2,873 Views

This week, through multiple attempts, I discovered that the original load balancing fails due to LAG, causing it to slow down and overheat. Therefore, a faster load balancing method is needed to accomplish the task. Additionally, a large number of background processes from users also affect the operation of certain cores, leading to an unsmooth gaming experience. This is my insight from this month's adjustments for your reference.

Thank you for your response!

0 Kudos
Reply