Are NumPy's math functions faster than Python's?

前端 未结 3 988
不思量自难忘°
不思量自难忘° 2020-11-27 16:00

I have a function defined by a combination of basic math functions (abs, cosh, sinh, exp, ...).

I was wondering if it makes a difference (in speed) to use, for examp

3条回答
  •  無奈伤痛
    2020-11-27 16:34

    In fact, on numpy array

    built in abs calls numpy's implementation via __abs__, see Why built-in functions like abs works on numpy array?

    So, in theory there shouldn't be much performance difference.

    import timeit
    
    x = np.random.standard_normal(10000)
    
    def pure_abs():
        return abs(x)
    
    def numpy_abs():
        return np.absolute(x)
    
    n = 10000
    
    t1 = timeit.timeit(pure_abs, number = n)
    print 'Pure Python abs:', t1
    t2 = timeit.timeit(numpy_abs, number = n)
    print 'Numpy abs:', t2
    Pure Python abs: 0.435754060745
    Numpy abs: 0.426516056061
    

提交回复
热议问题