Question

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;
        }
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top