简体   繁体   English

如何使这些嵌套的for循环更有效?

[英]How to make these nested for-loop more efficient?

I have two lists: 我有两个清单:

  1. ActiveExchange = [] ActiveExchange = []
  2. ActiveStock = [] ActiveStock = []

My code is very sequential in nature and I'm trying to optimize it: 我的代码本质上是非常顺序的,我正在尝试对其进行优化:

for exchange in ActiveExchange:
    for stock in Activestock:
        ...
        ...
        ...

However, it seems to be highly inefficient due to the for-loop. 但是,由于for循环,它似乎效率很低。 What can i do to make it run more efficiently? 我该怎么做才能使其更有效地运行?

  1. Does it just seem unefficient or did you run it and it took too long? 它只是看起来效率低下还是您运行了它并且花费了太长时间? If you just think its unefficient - test it. 如果您只是认为它效率低下,请对其进行测试。 And don't uptimize a not existing problem. 并且不要优化一个不存在的问题。 You can use your time more efficiently. 您可以更有效地利用时间。

Anything else will be case-dependent. 其他任何情况都将视情况而定。 Like: 喜欢:

  1. if you are searching for one or tow items in ActiveStack for every elemant in ActiveExchange,make the ActiveStack a hash. 如果要在ActiveStack中为ActiveExchange中的每个元素搜索一个或两个项目,请使ActiveStack成为哈希。
  2. If you have if statements, and the statement depends on one variable only, make it the outter one. 如果您具有if语句,并且该语句仅取决于一个变量,则使其成为外面的变量。 that way you opyimize brach prediction. 这样,您就可以优化分支预测。 This may be done automaticlly by the compiler. 这可以由编译器自动完成。
  3. If you want to manipulate/read all pairs - you cannot optimize it. 如果要操纵/读取所有对,则无法对其进行优化。

C/C++ and Python are have row-major arrays. C / C ++和Python具有以行为主的数组。 If you are stepping through an array, list, vector, etc, be sure to do this: 如果要遍历数组,列表,向量等,请确保执行以下操作:

for i in range(25):
  for j in range(25):
    A[j][i] *= 1

rather than: 而不是:

for i in range(25):
  for j in range(25):
    A[i][j] *= 1

That can make a difference of 3-6 times in performance. 这样可以使性能相差3-6倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM