Reputation: 58985
In Cython it is known that an undeclared variable type carries more overhead that slows down the whole process.
If this unknown variable type is used inside a nested loop like:
def test(b, c, m, n, p):
ctype double a
for i in range(m)
for j in range(n)
for k in range(p)
a = b + c
return a
the overhead can be much higher. In a problem with many variables one can easily forget to declare one or another type, and the compiler will not raise a warning since Cython does the required overhead.
Is there a command in Cython to force all variables to be explicitly declared?
Upvotes: 1
Views: 575
Reputation: 58985
One should surely start with the solution proposed by the accepted answer.
Another great solution is to put the critical part of the code inside a with nogil:
block. This will throw a compilation error if any Python API is called.
Usually the critical part is a deep for loop:
with nogil:
for i in range(m):
for j in range(n):
for k in range(p):
for l in range(q):
...
Upvotes: 1
Reputation:
In Cython it is known that an undeclared variable type carries more overhead that slows down the whole process.
You know wrong, there is (limited) type inference, and not every type annotation improves performance (e.g. unwrapping an int argument and then passing it to Python unchanged, wrapping it back up in a new object). A more useful metric is the amount of CPython API calls, which is what cython -a
tells you.
Upvotes: 3