Pregunta

Doing very complex BigInteger operations are very slow e.g.

BigInteger.Pow(BigInteger(2),3231233282348);

I was wondering if there is any way I could multi thread any of these basic math functions.

¿Fue útil?

Solución

It depends on the math function but I really can't see how you could speed up basic math functions. For these sort of calculations the next step in the process would typically depend on the previous step in the process. Threading would only really help where you have portions of a calculation that can be calculated independently. These could then be combined in a final step to produce the result. You would need to break up these calculations yourself into the portions that can run concurrently.

For example:

If you had a formula with 2 * 3 + 3 * 4. You could run two threads, the first calculating 2 * 3 and the second 3 * 4. You could then pull the results together at the end and sum the two results. You would need to work out how to break down the calculation into something smaller and then thread those accordingly.

In your example with power you could work out the following in 4 threads and then combine the results at the end by multiplying the results:

BigInteger.Pow(BigInteger(2),807808320587);
BigInteger.Pow(BigInteger(2),807808320587);
BigInteger.Pow(BigInteger(2),807808320587);
BigInteger.Pow(BigInteger(2),807808320587);

This would not save you any time at all because all 4 cores would be thrashing around trying to work out the same thing and you would just multiple them by each other at the end which is what a single threaded solution would do anyway. It would even be much slower on some processors as they will often speed up one core if the others are idle. I broke this up using the same thing as breaking up a 2^5 into 2^2 * 2^3.

Otros consejos

The answer of

 BigInteger.Pow(BigInteger(2), 3231233282348);

will contain

  Log(2)/Log(10) * 3231233282348 == 9.727e11 

digits; so it requires 900 GB to write the answer. That's why it that slow

If you're using .NET 4.5 read about async await:

http://blog.stephencleary.com/2012/02/async-and-await.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top