[Python] Performance difference while calling similar, very simple functions in Python

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm confused. I defined two silly functions:

    def test_mul(r,f):
    for i in range(1000):
    x=r*8+f

    def test_add(r,f):
    for i in range(1000):
    x=r+f


    test_add is some 20% faster than test_mul, and that sounds reasonable (just under 17 secs for 1 million repetitions vs just under 22 secs on my notebook). Now let's use global variables instead of arguments

    r=3
    f=5

    def test_mul2():
    for i in range(1000):
    x=r*8+f

    def test_add2():
    for i in range(1000):
    x=r+f


    These are incredibly faster, and moreover, test_mul2, which performs a multiplication and a sum, is consistently slightly faster than test_add2, which only performs a sum: around 11 millisecs vs around 12.

    timeit('test_add(3,5)',globals=globals())
    16.795306700048968
    timeit('test_mul(3,5)',globals=globals())
    21.756636400008574

    timeit('test_add2',globals=globals())
    0.012141100014559925
    timeit('test_mul2',globals=globals())
    0.010826400015503168


    Can someone explain what's happening (Py 3.12 on Win 11)?

    Continue reading...

Compartilhe esta Página