-1

I want to do some computation within a for loop:

for (int i=0; i< Math.Pow(10,8) ;i++){
  //do some computation
}

but when I run, it only uses one of my cpu cores, (I see in task manager that my program uses 50% of cpu).

how can I use both cores? does it needs threading?

and also if it needs multi-threading ,I cannot break the loop because it fills an array and uses it as index increments ,so then what is the solution (if threading is needed).

for example in the code below , I fill array P as i increments and I use the array dynamically.

void f(){/*do some computation*/}
double[] P;
for (int i=0; i< Math.Pow(10,8) ;i++){
   if (some conditions with index i and f and array P occurs )
      P[i]=f;

}

my laptop is intel core 2 dou 2.2 GH.

abdolahS
  • 663
  • 12
  • 35
  • 1
    For finding prime numbers, you can definitely use the parallel for loop like Dennis suggested below. To improve things even further, I would suggest reading http://stackoverflow.com/questions/4700107/how-do-i-implement-the-sieve-of-eratosthenes-using-multithreaded-c it might provide some hints for you. – RvdV79 Mar 04 '14 at 11:20

2 Answers2

4

does it needs threading?

Yes, it does. You can use parallel for loop implementation from TPL:

        Parallel.For(0, (int)Math.Pow(10, 8),
            i =>
            {
                // do some computation
            });

Of course, this solution is applicable, if the value for every item in your array could be calculated separately from others.

Dennis
  • 37,026
  • 10
  • 82
  • 150
  • could you post what conditions with contents of `P` exactly being checked? – Dennis Mar 04 '14 at 10:51
  • suppose my algorithm is for finding prime numbers and each time when it finds a prime (if i% P[j] !=0 for all j's up to now) saves it in P[j+1] .(I know that there are very better algorithms for prime number testing) – abdolahS Mar 04 '14 at 10:59
  • 1
    If I understand you correctly, you can't make your calculations in parallel. – Dennis Mar 04 '14 at 12:16
1

Have a look at that : http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for(v=vs.110).aspx You'll find plenty of examples across the web.