Skip to content

Instantly share code, notes, and snippets.

@winocm
Forked from kbeckmann/bad_cpu.py
Last active December 14, 2021 13:54
Show Gist options
  • Save winocm/95f4ad57f93de698683cd2c8b4a842b1 to your computer and use it in GitHub Desktop.
Save winocm/95f4ad57f93de698683cd2c8b4a842b1 to your computer and use it in GitHub Desktop.
import time
import psutil
import multiprocessing as mp
from multiprocessing import Process
from ctypes import *
threadpin = CDLL(".\\threadpin.dll")
print(threadpin.thread_assign_to_processor)
def f(thread, duty, freq, q):
# p = psutil.Process()
# p.cpu_affinity([thread])
threadpin.thread_assign_to_processor(thread)
while True:
while not q.empty():
duty = float(q.get())
t0 = time.time()
while time.time() - t0 < duty / freq:
pass
t1 = time.time()
dest = t0 + 1 / freq
delay = dest - t1
if delay > 0:
time.sleep(delay)
if __name__ == '__main__':
p = psutil.Process()
threads = range(0, 128) # p.cpu_affinity()
workers = []
ctx = mp.get_context('spawn')
bpp = 4
width = 16
height = 8
fps = 2.0
gain = 1.0
for thread in threads:
q = ctx.Queue()
duty = 1
# Uncomment to fade from 0 to 100% from left to right
# duty = (thread % width) / (width - 1)
p = Process(target=f, args=(thread, duty, fps, q))
p.start()
workers.append({"p": p, "q": q})
# ffmpeg -i input.mp4 -vf scale=16:8,hue=s=0 -r 2 -c:v rawvideo -pix_fmt rgb32 out.rgb
# scale=width:height
# -r : fps
f = open("out.rgb", "rb")
video = f.read()
f.close()
frames = len(video) // (bpp * width * height)
for frame in range(frames):
for j, worker in enumerate(workers):
pixel = video[frame * bpp * width * height + j * bpp] / 256. * gain
worker["q"].put(1.0 - pixel)
time.sleep(1 / fps)
for worker in workers:
worker["p"].kill()
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <windows.h>
void
thread_assign_to_processor(uint32_t processor)
{
uint32_t num_groups;
uint32_t num_processors;
uint32_t target_group;
uint32_t target_processor;
HANDLE thread;
bool found;
num_groups = GetActiveProcessorGroupCount();
thread = GetCurrentThread();
for (uint32_t idx = 0; idx < num_groups; idx++) {
UCHAR node_number;
num_processors = GetActiveProcessorCount(idx);
GetNumaProcessorNode (idx, &node_number);
if (num_processors > processor) {
target_group = idx;
target_processor = num_processors - GetActiveProcessorCount(idx) + processor;
found = true;
break;
}
processor -= num_processors;
}
if (found) {
PROCESSOR_NUMBER pn;
GROUP_AFFINITY ga;
ga.Group = target_group;
ga.Mask = 1ULL << target_processor;
ga.Reserved[0] = 0;
ga.Reserved[1] = 0;
ga.Reserved[2] = 0;
SetThreadGroupAffinity(thread, &ga, NULL);
pn.Number = target_processor;
pn.Group = target_group;
pn.Reserved = 0;
SetThreadIdealProcessorEx(thread, &pn, NULL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment