Ab Laxman
Ab Laxman

Reputation: 55

How to check the no. of cores and total ram in a pc and do process using different techniques?

I want my app to check for the no. of cores and amount of RAM in the pc that is running it and if the values are higher than certain desired values then run my code using parallel methods (e.x. Parallel.For/Foreach and PLINQ) and the values are lower use normal (i.e. not parallel) methods, something like

int corecount = Environment.ProcessorCount;
ComputerInfo myCompInfo = new ComputerInfo();
var totalram = myCompInfo.TotalPhysicalMemory/ 1024 / 1024;

if (corecount>2 && totalram>1000)
{
    //use parallel methods
}
else
{
    //use normal methods
}

Is this the right way of doing it?

Upvotes: 1

Views: 53

Answers (1)

displayName
displayName

Reputation: 14369

There is a better way, if not, a certain right way.


General Idea:

  • Write code that executes in parallel using PLINQ/Parallel.For().
  • Then calculate the degree of parallelism, with the value being 1 when the machine is not capable enough.

A sample PLINQ code can look like:

public static void MyParallelMethod()
{
    var dop = GetDegreeOfParallelism();

    //use parallel methods and pass them the degree of parallelism

    var result = linqSource
        .AsParallel()
        .WithDegreeOfParallelism(dop)
        .Where(...)
        .Select(...)
        .
        ...;
}

private static int GetDegreeOfParallelism()
{
    var corecount = Environment.ProcessorCount;
    var myCompInfo = new ComputerInfo();
    var availableRam = myCompInfo.TotalPhysicalMemory / 1024 / 1024;

    //Devise your logic to calculate dop...
    //Return 1 when no parallelism is possible.

    return dop;
}

Upvotes: 1

Related Questions