python struct pack speed up inside function
Question: I'm testing python's struct pack/unpack performance and notice it'll speed up
if put inside a function:

    
    
    import time
    import struct
    from io import BytesIO
    
    def pack(b):
        for i in range(10000000):
            b.write(struct.pack('!i', i))
    
    b = BytesIO()
    start = time.time()
    pack(b)
    end = time.time()
    print(end - start)
    
    b2 = BytesIO()
    start = time.time()
    for i in range(10000000):
        b2.write(struct.pack('!i', i))
    end = time.time()
    print(end - start)
    

Running this gives

    
    
    2.639040946960449
    3.0683419704437256
    

The codes are the same, while the function is faster.

Why is this?


Answer: A loop inside a function is faster than the same loop at the global level:

    
    
    from timeit import default_timer as timer
    
    N = 10000000
    
    def f():
        for i in range(N):
            pass
    
    start = timer()
    for i in range(N):
        pass
    print("global %.2f" % (timer() - start,))
    
    start = timer()
    f()
    print("function %.2f" % (timer() - start,))
    

Output:

    
    
    global 0.71
    function 0.40
    

It may be explained by the difference in the speed of global vs. local
namespace access in CPython.

