Click here to Skip to main content
15,881,600 members
Home / Discussions / C / C++ / MFC
   

C / C++ / MFC

 
QuestionCPU Usage Pin
Richard Andrew x6419-May-23 15:56
professionalRichard Andrew x6419-May-23 15:56 
AnswerRe: CPU Usage Pin
Dave Kreskowiak19-May-23 17:48
mveDave Kreskowiak19-May-23 17:48 
GeneralRe: CPU Usage Pin
harold aptroot19-May-23 18:53
harold aptroot19-May-23 18:53 
AnswerRe: CPU Usage Pin
Greg Utas20-May-23 0:13
professionalGreg Utas20-May-23 0:13 
AnswerRe: CPU Usage Pin
Gerry Schmitz20-May-23 4:04
mveGerry Schmitz20-May-23 4:04 
AnswerRe: CPU Usage Pin
Randor 20-May-23 6:38
professional Randor 20-May-23 6:38 
GeneralRe: CPU Usage Pin
Richard Andrew x6420-May-23 10:21
professionalRichard Andrew x6420-May-23 10:21 
GeneralRe: CPU Usage Pin
Dave Kreskowiak20-May-23 19:30
mveDave Kreskowiak20-May-23 19:30 
I know this is the C/C++ forum, but here's an example of how to do this in C#. It was an interesting little research project.

The result can be seen in Task Manager quite easily. The CPU is limited to an AVERAGE of 20% in this example. It'll go as low as 8% and as high as 25% on my 13900K.

C#
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace CsJobObjectSandbox
{
    internal class Program
    {
        [StructLayout(LayoutKind.Explicit, Size = 8)]
        public struct JobObject_CPU_Rate_Control_Information
        {
            [FieldOffset(0)]
            public uint ControlFlags;

            [FieldOffset(4)]
            public uint CpuRate;
            [FieldOffset(4)]
            public uint Weight;

            [FieldOffset(4)]
            public ushort MinRate;
            [FieldOffset(6)]
            public ushort MaxRate;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int nLength;
            public IntPtr lpSecurityDescriptor;
            public int bInheritHandle;
        }

        public enum JobObject_Info_Class
        {
            BasicLimitInformation = 2,
            BasicUiRestrictions = 4,
            SecurityLimitInformation = 5,
            EndOfJobItmeInformation = 6,
            AssociateCompletionPortInformation = 7,
            ExtendedLimitInformation = 9,
            GroupInformation = 11,
            NoticiationLimitInformation = 12,
            GroupInformationEx = 14,
            CpuRateControlInformation = 15,
            NetRateControlinformation = 32,
            NotificationLimitInformation = 33,
            LimitViolationInformation2 = 34
        }

        private const uint JOBOBJECT_CPU_RATE_CONTROL_ENABLE = 0x1;
        private const uint JOBOBJECT_CPU_RATE_CONTROL_WEIGHT_BASED = 0x2;
        private const uint JOBOBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x4;
        private const uint JOBOBJECT_CPU_RATE_CONTROL_NOTIFY = 0x8;
        private const uint JOBOBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE = 0x10;

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr CreateJobObject([In] ref SECURITY_ATTRIBUTES lpJobAttributes, string lpName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern bool SetInformationJobObject([In] IntPtr hJob, [In] JobObject_Info_Class jobObjectInfoClass, IntPtr lpJobObjectInfo, int cbJobObjectInfoLength);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr AssignProcessToJobObject([In] IntPtr hJob, [In] IntPtr hprocess);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern bool CloseHandle([In] IntPtr hObject);

        
        static void Main(string[] args)
        {
            // Setup security for the job object. In this case, use the defaults;
            SECURITY_ATTRIBUTES attributes = new();
            attributes.nLength = Marshal.SizeOf(attributes);
            attributes.lpSecurityDescriptor = IntPtr.Zero;
            attributes.bInheritHandle = 0;

            // Create a new job object and set it up for limiting CPU usage to 20%.
            IntPtr jobHandle = CreateJobObject(ref attributes, "SandboxJobObject");
            JobObject_CPU_Rate_Control_Information cpuLimitInfo = new()
            {
                ControlFlags = JOBOBJECT_CPU_RATE_CONTROL_ENABLE | JOBOBJECT_CPU_RATE_CONTROL_HARD_CAP,
                CpuRate = 2000
            };

            // Copy the managed structure we used for setup to a block of unmanaged memory.
            int size = Marshal.SizeOf(typeof(JobObject_CPU_Rate_Control_Information));
            IntPtr infoPointer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(cpuLimitInfo, infoPointer, false);

            // Make the call to set the job object to limit CPU usage...
            bool result = SetInformationJobObject(jobHandle, JobObject_Info_Class.CpuRateControlInformation, infoPointer, size);

            // Did it work?
            if (result)
            {
                // Yep! free the unmanaged block of memory. We don't need it anymore.
                Marshal.FreeHGlobal(infoPointer);

                // Grab the process handle for this process.
                IntPtr processHandle = Process.GetCurrentProcess().Handle;

                // Assign this process to use the job object we created.
                _ = AssignProcessToJobObject(jobHandle, processHandle);

                // Go do some work to test if this worked!
                Task task = TestMethodAsync();
                task.Wait();
            }

            // Oh, when we're done with the job object, make sure to free it!
            CloseHandle(jobHandle);
        }

        // Some long running work that uses all avaialable cores.
        static Task TestMethodAsync()
        {
            return Task.Factory.StartNew(() =>
            {
                long y = 0;

                Parallel.For((long)0, (long)10000000000, (x) =>
                {
                    y = x++ * 2;
                });
            });
        }
    }
}


QuestionRe: CPU Usage Pin
David Crow22-May-23 7:49
David Crow22-May-23 7:49 
AnswerRe: CPU Usage Pin
Dave Kreskowiak22-May-23 8:43
mveDave Kreskowiak22-May-23 8:43 
GeneralRe: CPU Usage Pin
Dave Kreskowiak20-May-23 10:28
mveDave Kreskowiak20-May-23 10:28 
QuestionA two-dimensional std::vector for use by all Pin
polcott18-May-23 10:06
polcott18-May-23 10:06 
AnswerRe: A two-dimensional std::vector for use by all Pin
Gerry Schmitz18-May-23 18:25
mveGerry Schmitz18-May-23 18:25 
GeneralRe: A two-dimensional std::vector for use by all Pin
Richard MacCutchan19-May-23 0:09
mveRichard MacCutchan19-May-23 0:09 
GeneralMessage Closed Pin
19-May-23 5:03
polcott19-May-23 5:03 
GeneralRe: A two-dimensional std::vector for use by all Pin
jschell19-May-23 7:49
jschell19-May-23 7:49 
QuestionNot able to set header and footer in excel on multiple (even or odd pages) Pin
I_am_nayak16-May-23 19:19
I_am_nayak16-May-23 19:19 
AnswerRe: Not able to set header and footer in excel on multiple (even or odd pages) Pin
David Crow17-May-23 2:23
David Crow17-May-23 2:23 
QuestionMessage Closed Pin
14-May-23 13:20
polcott14-May-23 13:20 
AnswerRe: Can D simulated by H terminate normally? Pin
Richard MacCutchan14-May-23 21:39
mveRichard MacCutchan14-May-23 21:39 
AnswerRe: Can D simulated by H terminate normally? Pin
jschell15-May-23 4:58
jschell15-May-23 4:58 
GeneralMessage Closed Pin
15-May-23 8:30
polcott15-May-23 8:30 
GeneralRe: Can D simulated by H terminate normally? Pin
harold aptroot15-May-23 9:20
harold aptroot15-May-23 9:20 
GeneralMessage Closed Pin
15-May-23 9:50
polcott15-May-23 9:50 
GeneralRe: Can D simulated by H terminate normally? Pin
harold aptroot15-May-23 10:03
harold aptroot15-May-23 10:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.