I’ve written many blog articles in the past that show that the performance of a piece of parallel code can vary dramatically based on the number of available cores. With that it mind, its obviously desirable even when given a machine with 8 cores that you test your code against a machine that could have substantially less. You can resort to task manager and set Process Affinity and reduce the number of cores available for the process, but this is tedious. There is a .NET API that allows access to controlling which cores to make available for a process. The API requires the use of a bitmask to identity which cores to use, that's a bit ( no pun intended) overkill for what I'm trying to do, so I created a facade that allows me to simply say use N cores.
public static class Cores
{
public static int Max
{
get
{
return Environment.ProcessorCount;
}
}
public static int CoresInUse
{
get
{
IntPtr cores =
Process.
GetCurrentProcess()
.ProcessorAffinity;
int nCores = 0;
while( cores != IntPtr.Zero )
{
if ( ((int)cores & 1) == 1 )
{
nCores++;
}
cores = (IntPtr)((int)cores >> 1);
}
return nCores;
}
set
{
if ((value < 1) || (value > Environment.ProcessorCount))
{
throw new ArgumentException("Illegal number of cores");
}
int cores = 1;
for (int nShift = 0; nShift < value-1; nShift++)
{
cores = 1 | (cores << 1);
}
Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)cores;
}
}
}
The following code prints out the number of active cores and then reduces the number of cores to 4
Console.WriteLine("Using {0} out of {1}" , Cores.CoresInUse , Cores.Max);
Cores.CoresInUse = 4;
Console.WriteLine("Using {0} out of {1}", Cores.CoresInUse, Cores.Max);
No comments:
Post a Comment