Introductory notes: trying to accelerate Python+Numpy code with Cython is a common problem and this question is an attempt to create a canonical question about what types of operation you can accelerate effectively. Although I try to illustrate with a specific example, it is meant as an illustration - please don't focus too much on the fairly meaningless example.
Also, I've contributed enough to Cython that I should declare an affiliation (given that I'm bringing the topic up)
Actual question
Suppose I have a function that tries to do numeric calculations on Numpy arrays. It uses fairly typical operations:
np.sin).a-b)import numpy as np
def some_func(a, b):
"""
a and b are 1D arrays
This is intended to be illustrative! Please don't focus on what it
actually does!
"""
transformed_a = np.zeros_like(a)
last = 0
for n in range(1, a.shape[0]):
an = a[n]
if an > 0:
delta = an - a[n-1]
transformed_a[n] = delta*last
else:
last = np.sin(an)
return transformed_a * b
a = np.random.randn(100)
b = np.linspace(0, 100, a.shape[0])
print(some_func(a, b))
Can I speed this up with Cython, and which parts would I expect to be able to speed up?