首页 > 解决方案 > 将python转换为cython时的变量类型

问题描述

我在 Python 中使用递归循环计算第一次通过时间到随机游走的 L 点。我已经编写了代码,但我想通过将其转换为 Cython 来优化它,但我没有使用 C 的经验,我不知道如何将此代码转换为适合优化,或者如何描述变量类型。任何帮助,将不胜感激。

%%cython
import numpy as np
cimport numpy as np

def f_passagetime_rec_cython(L,start=[0,0]):


    T=10000000
    r = np.zeros((T,2))
    r[0]=start
    delta = 1
    greater=False
    for i in range (0,T - 1):
        if r[i,0]<=L:
            theta = np.random.uniform(0, 2*np.pi, size = None)
            r[i + 1,0] = r[i,0] + np.cos(theta)*delta                
            r[i + 1,1] = r[i,1] + np.sin(theta)*delta
        else:
            greater=True
            return i


    if greater==False:
        x=f_passagetime_rec_cython(L,r[-1])
        i=x+1+i

    return i

标签: pythoncperformancecython

解决方案


这就是我建议cythonizing的方式。创建一个setup.py文件:

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("function.pyx")
)

那么你的function.pyx文件基本上就是你的python代码:

import numpy as np

def f_passagetime_rec_cython(L,start=[0,0]):


    T=10000000
    r = np.zeros((T,2))
    r[0]=start
    delta = 1
    greater=False
    for i in range (0,T - 1):
        if r[i,0]<=L:
            theta = np.random.uniform(0, 2*np.pi, size = None)
            r[i + 1,0] = r[i,0] + np.cos(theta)*delta                
            r[i + 1,1] = r[i,1] + np.sin(theta)*delta
        else:
            greater=True
            return i


    if greater==False:
        x=f_passagetime_rec_cython(L,r[-1])
        i=x+1+i

    return i

然后在终端中构建 cythonized 函数,如下所示:

python setup.py build_ext --inplace

您可以通过使用标准 Python 语法导入来访问 cythonised 函数:

import function
function.f_passagetime_rec_cython(10)

推荐阅读