Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Maximum Performance of a loop

Tags:

c#

cpu

I am trying to calculate on a BigInteger variable then add the result to the database .

What happen is sth like this :

            for (BigInteger i = 0; i < ABigIntegerVariable; i++)
        {
            // add to db and calculate on a BigInteger
        }

So the problem is when I see CPU Usage on Task Manager it is only about 8% ! and this loop takes about 1 hour or more !!!

So it is not necessary for me to use computer while it is trying to calculate and add to database .

Would you pls tell me how to use the CPU with a high percentage of calculation and improve this process to have a faster calculation ?!

Thank you

like image 953
Mohammad Sina Karvandi Avatar asked Dec 19 '22 05:12

Mohammad Sina Karvandi


1 Answers

This is for multiple reasons:

1. your for loop runs on single thread,
2. you insert data into database in each iteration, instead of doing it in batch after processing of the loop is finished.

Proposed solutions:

1. You can try to use Parallel.For method to speed up the 1. reason.

Example: https://msdn.microsoft.com/en-us/library/dd460713(v=vs.110).aspx

2. You can move code responsible for saving the data from your for loop out of it to speed up the 2. reason.

like image 129
Andrew B Avatar answered Dec 22 '22 01:12

Andrew B