重写 if 条件以在 python 中加速

问题描述

我在函数中有以下带有 if 语句的代码。当我运行它会花费很长时间,这是一种重写 if 条件的方法还是一种加速此示例代码的方法?

import numpy as np

def func(S,R,H):
    ST =  S * R
    if ST <= - H:
      result = - H
    elif ST >= - H and ST < 0:
      result = ST
    else:
      result = min(ST,H)
    return result

y=[]
t1= time()
for x in np.arange(0,10000,0.001): 
    y.append(func(3,5,x))
t2 = time()
print("time with numpy arange:",t2-t1)

运行代码所需的时间:

 10 s

这是真实代码的复制示例,在真实代码中 ST 变成负值和正值,我们可以保留条件,但将 if 语句更改为其他内容可能有助于更快地执行任务!

解决方法

如果您希望您的函数参数仍然可用,您需要以创造性的方式使用布尔索引并将您的函数替换为:

from time import time
import numpy as np

ran = np.arange(-10,10,1)
s = 2
r = 3

st =  s * r

def func(S,R,H):
    ST =  S * R
    if ST <= - H:
      result = - H
    elif ST >= - H and ST < 0:
      result = ST
    else:
      result = min(ST,H)
    return result

# calculate with function
a = []
t1 = time()
for x in ran:
    a.append(func(s,r,x))
t2 = time()
print("time with function:",t2 - t1)
a = np.array(a)

# calculate with numpy
y = np.copy(ran)
neg_y = np.copy(y) * -1

# creative boolean indexing
t1 = time()
y[st <= neg_y] = neg_y[st <= neg_y]
if st < 0:
  y[st >= neg_y] = st
else:
  alike = np.full(ran.shape,st)[st >= neg_y]
  y[st > neg_y] = np.where(y[st > neg_y] > st,st,y[st > neg_y])
t2 = time()

print(a)
print(y)
print("time with numpy indexing:",t2 - t1)

会给你(时间省略):

# s=2,r=3
[10  9  8  7  6  5  4  3  2  1  0 -1 -2 -3 -4 -5 -6 -6 -6 -6] # function
[10  9  8  7  6  5  4  3  2  1  0 -1 -2 -3 -4 -5 -6 -6 -6 -6] # numpy

# s=-2,s=3
[10  9  8  7  6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  6  6  6] # function
[10  9  8  7  6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  6  6  6] # numpy

您可能需要稍微调整一下。

使用

ran = np.arange(-1000,1000,0.001)

我得到以下时间 (s=3,r=5):

time with function: 5.606577634811401
[1000.     999.999  999.998 ...   15.      15.      15.   ]
[1000.     999.999  999.998 ...   15.      15.      15.   ]
time with numpy indexing: 0.06600046157836914

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...