- 1 year ago
how windows JobObject set limit on cpu usage?
Comment
1 / 1
To set a limit on CPU usage using Windows JobObjects, you can use the SetInformationJobObject
function with the JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
structure.
Here's an example of how to set a limit of 50% CPU usage:
pythonimport ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
# define constants
JOB_OBJECT_LIMIT_CPU_RATE_CONTROL = 0x00040000
JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x0001
JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x0002
class JOBOBJECT_CPU_RATE_CONTROL_INFORMATION(ctypes.Structure):
_fields_ = [('ControlFlags', ctypes.c_uint32),
('CpuRate', ctypes.c_uint32),
('MaxRate', ctypes.c_uint32)]
# create the job object
job_object = kernel32.CreateJobObjectW(None, None)
# set the CPU limit
cpu_limit = 50 # in percent
ctrl_flags = JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP
cpu_rate_info = JOBOBJECT_CPU_RATE_CONTROL_INFORMATION(ctrl_flags, cpu_limit * 100, 0)
kernel32.SetInformationJobObject(job_object, 37, ctypes.byref(cpu_rate_info), ctypes.sizeof(cpu_rate_info))
In this example, the JOB_OBJECT_CPU_RATE_CONTROL_ENABLE
flag enables CPU rate control for the job object, and the JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP
flag indicates that the specified CPU rate is a hard limit. The JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
structure specifies the CPU rate as a percentage of the total CPU usage.
Note that the SetInformationJobObject
function may fail if the job object is already running or if the calling process does not have permission to set the CPU rate control information.