Improve performance on numpy trigger functions

I have a pretty big code that I need to optimize. After some analysis using time.time(), I found that the line that takes the longest processing time (it runs thousands of times) is like this:

A = np.cos(a) * np.cos(b) - np.sin(a) * np.sin(b) * np.sin(c - d)

where all variables can be randomly defined:

N = 5000
a = np.random.uniform(0., 10., N)
b = np.random.uniform(0., 50., N)
c = np.random.uniform(0., 30., N)
d = np.random.uniform(0., 25., N)

Is there a way to improve computing performance A? Since I already use numpy, I have almost no ideas.

+4
source share
2 answers

. , . . func1 func2 , func2 . .

import numpy as np

def func1(a, b, c, d):
    A = np.cos(a) * np.cos(b) - np.sin(a) * np.sin(b) * np.sin(c - d)
    return A

def func2(a, b, c, d):
    s = np.sin(c - d)
    A = 0.5*((1 - s)*np.cos(a - b) + (1 + s)*np.cos(a + b))
    return A

N = 5000:

In [48]: %timeit func1(a, b, c, d)
1000 loops, best of 3: 374 µs per loop

In [49]: %timeit func2(a, b, c, d)
1000 loops, best of 3: 241 µs per loop
+7

Python, Numba, Cython, Pythran - ?

Pythran. :

:

  • Python + numpy: 1000 , 3: 1.43
  • Pythran: 1000 , 3: 777usec
  • Pythran + SIMD: 1000 , 3: 488 usec

, :

  • Python + numpy: 1000 , 3: 1.05
  • Pythran: 1000 , 3: 646 usec .
  • Pythran + SIMD: 1000 , 3: 425 usec

N = 5000

  • *:

:

# pythran export func1(float[], float[], float[], float[])
# pythran export func2(float[], float[], float[], float[])
import numpy as np

def func1(a, b, c, d):
    A = np.cos(a) * np.cos(b) - np.sin(a) * np.sin(b) * np.sin(c - d)
    return A

def func2(a, b, c, d):
    s = np.sin(c - d)
    A = 0.5*((1 - s)*np.cos(a - b) + (1 + s)*np.cos(a + b))
    return A

:

$ pythran test.py  # Default compilation
$ pythran test.py -march=native -DUSE_BOOST_SIMD  # Pythran with code vectorization
+3

Source: https://habr.com/ru/post/1622535/


All Articles