简体   繁体   中英

Speed up PI calculation using async?

I have method that calculates pi. I was just wonder if I could make this faster using C#5's async/await features?

public decimal CalculatePi(int measure)
        {
            var target = measure;
            decimal current = 3;
            var incrementing = false;
            var inner = (decimal)1.0;
            while (current < target)
            {
                if (!incrementing)
                {
                    inner = inner - (1/current);
                    current += 2;
                    incrementing = true;
                }
                if (incrementing)
                {
                    inner = inner + (1/current);
                    current += 2;
                    incrementing = false;
                }

            }
            return 4*inner;
        }

Async and await are best used when accessing other resources like the network or the hard drive where speeds might be slower than you want. Using it on purely processor code like this will only make your code share the processor with the rest of your code (the original calling code that started this method) much like starting a thread. Either it's slowed down by your other code continuing to do things, or that other code hits await and continues as if it were synchronous. There would be no major benefit to using async/await.

I don't know if the calculation of PI itself is correct, but your algorithm is not a good candidate for multithreading.

Actually, your algorithm is sequential and with very small code. Context switching will add a lot of overhead and you will loose any benefits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM