Nested loops are faster!

While solving a problem on hackerrank, I had to use for nested loops in problem related to 2D array.  Then, I realised I should use single loop rather than nested and then, I tried myself both the approaches to check which approach is better and faster.

Every time for similar iterations, nested loops were faster than the single loops.  Below is the python code to verify yourself.
The following code takes the inputs 10, 20, 50, 100 and outputs the time required by both the approaches.

Python Code:


import time

def loopinloop(n):
    StartTime = time.time()
    for i in range(0, n):
        for j in range(0, n):
            # Do nothing
            continue;
    return (time.time() - StartTime);

def loopalone(n):
    StartTime = time.time()
    for i in range(0, n**2):
        continue;
    return (time.time() - StartTime);

if __name__ == "__main__":
    number = [10, 20, 50, 100];
    withinloops = [loopinloop(num) for num in number];
    oneloop = [loopalone(num) for num in number];
    print("withinloops = {0}".format(withinloops))
    print("one loop = {0}".format(oneloop))

Output:

withinloops = [1.0013580322265625e-05, 1.9073486328125e-05, 7.987022399902344e-05, 0.0002682209014892578]
one loop = [4.0531158447265625e-06, 1.1920928955078125e-05, 9.298324584960938e-05, 0.0003771781921386719]


As the above code and its output suggests, nested loops are faster which is quite a contradiction in itself i.e. O(n^2) is faster than O(n).  But after searching a little I found this Stackoverflow answer.

Thus, single loop is not always faster than nested loops.  It depends on the statements it is executing.  Hope this helps :)

Till then,

To Infinity and Beyond!

Moving!

It's been a long time, since I published anything here, but that doesn't mean I stop writing, I kept writing everyday, just didn...