Error compiling Cython file: ------------------------------------------------------------ ... cdef int i i = 2.0 ^ ------------------------------------------------------------
Cannot assign type'double' to 'int'
当需要强制类型转换时,只需要使用<目标类型>:
1 2 3 4 5 6
In [2]: %%cython cdef int a = 1 cdef double b b = <double> a print(b) 1.0
以Fibonacci为例,看一下使用Cython后的速度提升:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
In [2]: %%cython deffib_cython(n): cdef int a = 0, b = 1 while b < n: print(b, end=' ') a, b = b, a + b print()
In [3]: deffib_python(n): a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a + b print()
In [4]: %timeit fib_cython(10) %timeit fib_python(10) 92 ns ± 0.652 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) 285 ns ± 1.47 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
函数
Cython中的函数,必须使用cdef语句声明函数的返回类型:
1 2
cdef int max_cython(int a, int b): return a if a > b else b
In [5]:%%cython cdef classPoint: cdef public double x cdef public double y def__init__(self, double x, double y): self.x = x self.y = y cdef double norm(Point p): return (p.x**2 + p.y**2)**0.5
In [6]: aim = Point(1.0, 2.0) In [7]: aim.x Out[7]: 1.0