For Loop UInt64 MaxValue Parallel Iteration Calculation Time

For Loop UInt64 MaxValue Parallel Iteration Calculation Time was an interesting Friday 30 Second question; if you were to iterate through a loop and you could parallelize your loop over 100 cores and each iteration took 1 nanosecond (i.e. 1 billion iterations per second) then how long would it take you to iterate over all the digits that could fit inside an UInt64?

e.g.

for (UInt64 i = 0; i < UInt64.MaxValue; i++)
{    
    ; // This operation takes 1 nanosecond and loop has no overhead
}

So this is really just a math situation. First we need to define what the value of Uint64.MaxValue is.  If we look up its value on MSDN, we know that it is a constant value of 18,446,744,073,709,551,615; that is, hexadecimal 0xFFFFFFFFFFFFFFFF.  Now at this point, it becomes common math.

This is the breakdown of how many operations will be happening per second in total across all cores.


Operations / Second / Thread = 1,000,000,000

Threads = 100

Operations / Second = 1,000,000,000 * 100 = 100,000,000,000

Now let’s apply it to the UInt64.MaxValue.

Seconds / Operation = 1 / 100,000,000,000

Total Seconds = Operations * (Seconds / Operation) = 18446744073709551615 * (1 / 100,000,000,000) = ~184467441

Minutes = 184467441/ 60 = 3074457

Hours = 3074457 / 60 = 51241

Days = 51241 / 24 = 2135

Weeks = 2135 / 7 = 305

Years = 305 / 52 = 5.86

The discussion and point that came out of this is a feature that was introduced in .Net 4.  It’s the concept of parallelizing your loops across all available processors with the Parallel.For<> loop. This will have its obvious benefits of being able to process at n times the amount of processors that are available.


Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile