Cython Profiling 实践

Cython Profiling 实践

  • 时间记录
    • python 实现
    • cython 实现1
    • cython 实现2
    • cython 实现3
  • TIPS
    • cProfile has no attribute runctx
    • ZeroDivisionError

时间记录

python 实现

# calc_pi.py

def recip_square(i):
    return 1. / i ** 2

def approx_pi(n=10000000):
    val = 0.
    for k in range(1, n + 1):
        val += recip_square(k)
    return (6 * val) ** .5

Cython Profiling 实践_第1张图片

cython 实现1

# cython: profile=True

# calc_pi.pyx

def recip_square(int i):
    return 1. / i ** 2

def approx_pi(int n=10000000):
    cdef double val = 0.
    cdef int k
    for k in range(1, n + 1):
        val += recip_square(k)
    return (6 * val) ** .5

Cython Profiling 实践_第2张图片

cython 实现2

# cython: profile=True

# calc_pi.pyx

cdef inline double recip_square(long long i):
    return 1. / (i * i)

def approx_pi(int n=10000000):
    cdef double val = 0.
    cdef int k
    for k in range(1, n + 1):
        val += recip_square(k)
    return (6 * val) ** .5

Cython Profiling 实践_第3张图片
注意: 速度增加主要靠inline(仅将i**2改为i*i几乎没有提升)

cython 实现3

# cython: profile=True

# calc_pi.pyx

cimport cython 

@cython.profile(False)
cdef inline double recip_square(long long i):
    return 1. / (i * i)

def approx_pi(int n=10000000):
    cdef double val = 0.
    cdef int k
    for k in range(1, n + 1):
        val += recip_square(k)
    return (6 * val) ** .5

Cython Profiling 实践_第4张图片

注意: 不要忘了加cimport cython

TIPS

cProfile has no attribute runctx

改文件名,不要使用 ‘profile’

profile.py -> profiler.py

ZeroDivisionError

def recip_square(int i):
    return 1. / i ** 2

改为

def recip_square(long long i):
    return 1. / i ** 2

防止整数太大,溢出为0

教程链接

你可能感兴趣的:(Cython)