Andy's observations as he continues to attempt to know all that is .NET...

Thursday, July 16, 2009

Testing on varying number of cores

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:

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...