我需要一种更有效的方法来完成以下任务:
for character in commandSequence:
if character == "F":
i += 1
gps = move(fullList.iloc[i-1, 2:].values,
distance, yaw, pitch, 'forward')
fullList.loc[i] = ['Forward', 'Actuated', gps[0], gps[1], gps[2]]
if character == "B":
i += 1
gps = move(fullList.iloc[i-1, 2:].values,
distance, yaw, pitch, 'backward')
fullList.loc[i] = ['Backwards', 'Actuated', gps[0], gps[1], gps[2]]
if character == "+":
yaw = yaw + radians(yaw)
if character == '-':
yaw = yaw - radians(yaw)
if character == "^":
pitch = pitch + radians(pitch)
if character == '.':
pitch = pitch - radians(pitch)
if character == '[':
fullList.iloc[i, 0] = 'Branch'
if character == ']':
if fullList['Description'].value_counts()['Branch'] > 0:
fullList.iloc[i, 0] = 'EOL'
upsideDown = fullList.reindex(
index=fullList.index[::-1]).dropna()
temp = upsideDown.iloc[upsideDown['Description'].eq(
'Branch').idxmax()].values
i += 1
fullList.iloc[i] = temp
典型的 commandSequence 如下所示:
FF + [+ [FB]-+ [FB]-+ [FB]-]-FBFF + [+ [FB]-+ [FB]-+ [FB]-]-FB
我需要对其进行优化,因为它是进化算法的一部分,因此存在很多迭代,这意味着我需要在任何可能的地方加快速度。
此外,如果有人可以提供一些指导,我会使用 profilestats 中的 profile 来计时代码,并输出以下内容:
21233966 function calls (20864585 primitive calls) in 46.433 seconds
Ordered by: cumulative time
List reduced from 1994 to 10 due to restriction <10>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.026 0.026 77.205 77.205 attempt_1.2.py:167(main)
1 0.003 0.003 31.960 31.960 draw.py:1(draw)
8 0.000 0.000 30.788 3.849 pyplot.py:236(show)
8 0.000 0.000 30.788 3.849 backend_bases.py:178(show)
1 0.000 0.000 30.762 30.762 backend_qt5.py:1115(mainloop)
180 0.406 0.002 27.591 0.153 attempt_1.2.py:32(toCoordinates)
180 0.284 0.002 17.542 0.097 attempt_1.2.py:104(absorbArea)
27339/19427 0.328 0.000 12.563 0.001 indexing.py:1463(__getitem__)
12228 0.200 0.000 10.900 0.001 indexing.py:2011(_getitem_tuple)
25706 0.202 0.000 9.834 0.000 indexing.py:2075(_getitem_axis)
所以我的说法正确吗?我需要加快 toCoordinates , absorbArea 和任何 __ getitem __ 的调用(无论是什么?)< / p>
答案 0 :(得分:1)
如果在这种情况下循环进入下一个字符,则可以在每个循环中添加continue,以避免对所有其他循环进行测试。
if character == "+":
yaw = yaw + radians(yaw)
continue
或使用if / elif
if condition1:
some actions
elif condition2:
以此类推
我看不到要加快循环速度了