Reputation: 4745
I want to create a small test that carries out some calculations to see how fast a processor will finish it in. For example I want to get the CPU info of a machine and then run a test like so:
public static double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
result += Math.Exp(Math.Log(i) / root);
}
return result;
}
private void buttonStart_Click(object sender, EventArgs e)
{
labelPhysicalProcessors.Text = "";
labelProcessorName.Text = "";
labelLogicalProcessors.Text = "";
labelCores.Text = "";
this.Cursor = Cursors.WaitCursor;
string physicalProcessors = String.Empty;
string processorName = String.Empty;
string logicalProcessors = String.Empty;
string coreCount = String.Empty;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
physicalProcessors = item["NumberOfProcessors"].ToString();
logicalProcessors = item["NumberOfLogicalProcessors"].ToString();
}
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
coreCount = item["NumberOfCores"].ToString();
processorName = item["Name"].ToString();
}
labelPhysicalProcessors.Text = physicalProcessors;
labelProcessorName.Text = processorName;
labelLogicalProcessors.Text = logicalProcessors;
labelCores.Text = coreCount;
var watch = Stopwatch.StartNew();
Parallel.For(2, 20, (i) =>
{
var result = SumRootN(i);
//Console.WriteLine("root {0} : {1} ", i, result);
});
labelTime.Text = watch.ElapsedMilliseconds.ToString() + " ms";
this.Cursor = Cursors.Arrow;
}
This produces:
I want to take advantage of the number of cores and logical processors on the CPU. How can I do this in C# i.e. if a machie has more cores then I want to split the work up onto each core so a machine with more cores and logical procesors will run the test faster.
Upvotes: 1
Views: 1602
Reputation: 171178
If you're building a benchmark you should control threading tightly. Start N threads manually where N is Environment.ProcessorCount
. Don't even use the Task
facility because it gives you less fairness guarantees.
You might want to increase the thread priority to reduce context switching induced timing jitter.
Upvotes: 1