首页 > 解决方案 > Cython 循环优化 | Python 循环 => Cython 循环

问题描述

我需要加快我的 Python 循环,我决定为此选择 Cython。不幸的是,我没有使用 Cython(和 C 语言)的经验。我在 Cython 中创建快速循环的尝试失败了。

这是我的 Python 函数:

def backtest(data, min_distance):
    balance = 1000
    
    t1 = time()

    for shift_1 in range(1, 101):
        for shift_2 in range(1, 101):
            for shift_3 in range(1, 101):
                if shift_2 > shift_1 * min_distance and shift_3 > shift_2 * min_distance:

                    pnls_shift_1 = data[shift_1 / 10]
                    pnls_shift_2 = data[shift_2 / 10]
                    pnls_shift_3 = data[shift_3 / 10]

                    for pnl in pnls_shift_1:
                        balance *= (pnls_shift_1[pnl] / 100) * (33 / 100)

                        if pnl in pnls_shift_2:
                            balance *= (pnls_shift_2[pnl] / 100) * (33 / 100)

                            if pnl in pnls_shift_3:
                                balance *= (pnls_shift_3[pnl] / 100) * (33 / 100)

    print(time() - t1)
    return balance

这是我尝试过的(Cython):

def backtest(dict data, float min_distance):
    cdef dict pnls_shift_1, pnls_shift_2, pnls_shift_3
    cdef int shift_1, shift_2, shift_3, pnl
    cdef int balance = 1000
    
    t1 = time()

    for shift_1 in range(1, 101):
        for shift_2 in range(1, 101):
            for shift_3 in range(1, 101):
                if shift_2 > shift_1 * min_distance and shift_3 > shift_2 * min_distance:
                    pnls_shift_1 = data[shift_1 / 10]
                    pnls_shift_2 = data[shift_2 / 10]
                    pnls_shift_3 = data[shift_3 / 10]

                    for pnl in pnls_shift_1:
                        balance *= (pnls_shift_1[pnl] / 100) * (33 / 100)

                        if pnl in pnls_shift_2:
                            balance *= (pnls_shift_2[pnl] / 100) * (33 / 100)

                            if pnl in pnls_shift_3:
                                balance *= (pnls_shift_3[pnl] / 100) * (33 / 100)

    print(time() - t1)
    return balance

结果,Cython 的执行时间甚至比原生 Python 更长。我认为问题出在我正在使用的 Python 字典中,但我不确定。我试图从 dict 切换到 list,但这很糟糕,最后什么也没发生。

我的输入字典如下所示: {0.1: {1: -2.5, 4: 3}, 0.2: {3: -1.5, 4: 1, 6: 0.24}, ... {10.0: {...}}}

如果有人建议在 Cython 中优化此循环,我将不胜感激。

标签: python-3.xdictionaryfor-loopoptimizationcython

解决方案


推荐阅读