I have a program that I would like to run on just one CPU so it doesn't take up too much system resources. The problem is, it makes a call into an external DLL that automatically uses all available CPU cores. I do not have the source code to the external DLL. How can I limit the DLL to only using one CPU?
EDIT: Thanks for the help, here is the code I used to limit to one CPU (Windows):
// Limit the process to only 1 thread so we don't chew up system resources
HANDLE ProcessHandle = GetCurrentProcess();
DWORD ProcessAffinityMask;
DWORD SystemAffinityMask;
if(GetProcessAffinityMask(ProcessHandle,&ProcessAffinityMask,&SystemAffinityMask)
&& SystemAffinityMask != 0)
{
// Limit to 1 thread by masking all but 1 bit of the system affinity mask
DWORD NewProcessAffinityMask = ((SystemAffinityMask-1) ^ SystemAffinityMask) & SystemAffinityMask;
SetProcessAffinityMask(ProcessHandle,NewProcessAffinityMask);
}
EDIT: Turns out Brannon's approach of setting process priority works even better for what I want, which is to keep the process from chewing up resources. Here's that code (Windows):
// Make the process low priority so we don't chew up system resources
HANDLE ProcessHandle = GetCurrentProcess();
SetPriorityClass(ProcessHandle,BELOW_NORMAL_PRIORITY_CLASS);
Setting processor affinity is the wrong approach. Let the OS handle scheduling.
If the machine is sitting idle, you want to use as much processor as you can. Otherwise you're doing less work for no reason. If the machine is busy, then you want to make use of "free" cycles and not adversely affect other processes.
Windows has this functionality built-in. The proper solution for this is to set the base priority of the process.
See http://msdn.microsoft.com/en-us/library/ms686219(VS.85).aspx for details on SetPriorityClass()
.
If you want to test this without writing any code, use Task Manager to change the priority of your process.