python-3.x - 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 中优化此循环,我将不胜感激。
解决方案
推荐阅读
- javascript - 在 json-server 中搜索
- python-3.x - 如何使用 .p12 证书对 rest api 进行身份验证
- c++ - 为什么 std::shuffle 采用右值引用?
- jquery - Jquery bind('beforeunload') 在 Chrome 弹出窗口中不起作用
- google-app-maker - 如何添加用户以在 google App Maker 项目上进行协作
- c# - C# DateTime 格式及比较
- django - 在 django 上设计和显示格式正确的数据。
- hadoop2 - 当我手动更改复制因子时会发生什么变化?
- angular - 后台实时进度
- c++ - 动态规划 - 原始计算器