In my program i want to detemine how many numbers have 9 digits how, many have 8 digits, etc. with this loop:
for (int i = 0; i < 60000000; i++)
{
if (a[i] >= 1000000000) { p[10] += 1; }
else if (a[i] >= 100000000) { p[9] += 1; }
else if (a[i] >= 10000000) { p[8] += 1; }
else if (a[i] >= 1000000) { p[7] += 1; }
else if (a[i] >= 100000) { p[6] += 1; }
else if (a[i] >= 10000) { p[5] += 1; }
else if (a[i] >= 1000) { p[4] += 1; }
else if (a[i] >= 100) { p[3] += 1; }
else if (a[i] >= 10) { p[2] += 1; }
else { p[1] += 1; }
}
I parallelized the loop like this:
void partiton(int f, int l, int[] p)
{
Parallel.Invoke(()=>calc(f,l/2,p),()=>calc(l/2,l,p));
}
void calc(int f, int l, int[] p)
{
for (int i = f; i < l; i++)
{
if (a[i] >= 1000000000) { p[10] += 1; }
else if (a[i] >= 100000000) { p[9] += 1; }
else if (a[i] >= 10000000) { p[8] += 1; }
else if (a[i] >= 1000000) { p[7] += 1; }
else if (a[i] >= 100000) { p[6] += 1; }
else if (a[i] >= 10000) { p[5] += 1; }
else if (a[i] >= 1000) { p[4] += 1; }
else if (a[i] >= 100) { p[3] += 1; }
else if (a[i] >= 10) { p[2] += 1; }
else { p[1] += 1; }
}
}
private void button1_Click(object sender, EventArgs e)
{
Stopwatch w = new Stopwatch();
w.Restart();
int f = 0;
int l = 60000000;
Parallel.Invoke(() => calc(f, l/2, p), () => calc(l/2, l, p));
w.Stop();
label1.Text = w.Elapsed.ToString();
}
But the benchmark is: Sequential : 0.3834 Parallel : 0.6864
Why is the parallel code slower? Is there something wrong with my code? My cpu is AMD Phenomâ„¢ II X4. Model, 955.
lockis slowing it down. (Especially with theint[] pobject which is written to by both threads.) - Der Kommissarpobjects, but you should be aware that usingp[x]+=1isn't thread safe since it reduces top[x] = p[x] + 1, and the thread can be interrupted between readingp[x]and writing back to it when another thread overwrites the value. On the topic of your question, you may be processor bound and threading introduces a lot of extra overhead with context switching. - Ron Beyer