[Python] Why Numpy fabs is much slower than abs?

Discussão em 'Python' iniciado por Stack, Junho 16, 2025.

  1. Stack

    Stack Membro Participativo

    This Python 3.12.7 script with Numpy 2.2.4 on AMD Ryzen 7 3800X:

    import numpy as np, timeit as ti

    a = np.random.rand(1000).astype(np.float32)
    print(f'Minimum, median and maximum execution time in us:')

    for fun in ('np.fabs(a)', 'np.abs(a)'):
    t = 10**6 * np.array(ti.repeat(stmt=fun, setup=fun, globals=globals(), number=1, repeat=999))
    print(f'{fun:20} {np.amin(t):8,.3f} {np.median(t):8,.3f} {np.amax(t):8,.3f}')


    produces these results:

    Minimum, median and maximum execution time in us:
    np.fabs(a) 1.813 1.843 4.929
    np.abs(a) 0.781 0.811 1.463


    indicating that np.fabs() is more than 2x slower than np.abs(), despite the latter having more functionality. What is the reason?

    Continue reading...

Compartilhe esta Página