0

有人能告诉我下面的疯狂循环结构是否可以用更好的方式重写吗?现在它做了我想做的一切。

    // xi and yi stand for x and y axis input index
    for (int xi = 0; xi < this.inputNumberOfColumnsAlongXAxis; xi++)
    {
        for (int yi = 0; yi < this.inputNumberOfColumnsAlongYAxis; yi++)
        {
            InputCell inputCell = new InputCell(xi, yi);
            Synapse synapse = new Synapse(inputCell);
            // add (inputDataScaleReductionOnXAxis * inputDataScaleReductionOnYAxis)
            // number of synapses to a proximalSegment.
            for (int x = 0; x < this.numberOfColumnsAlongXAxis; x++)
            {
                for (int y = 0; y < this.numberOfColumnsAlongYAxis; y++)
                {
                    int inputX =
                        (int)Math.round(x * inputDataScaleReductionOnXAxis);
                    int inputY =
                        (int)Math.round(y * inputDataScaleReductionOnYAxis);
                    this.columns[(y * this.numberOfColumnsAlongXAxis) + x] =
                        new Column(this, inputX, inputY, x, y);

                    // only add the square of synapses directly under the proximal segment
                    while (xi < this.inputDataScaleReductionOnXAxis * (x + 1))
                    {
                        while (yi < this.inputDataScaleReductionOnYAxis * (y + 1))
                        {
                            this.getColumn(x, y).getProximalSegment().addSynapse(synapse);
                        }
                    }
                 }
             }
         }
     }
4

2 回答 2

0

看起来您有一个二维数据结构的单元格和一个O(N^3)初始化过程,其中N是单元格的数量。这看起来有点贵……但如果 N 非常大或该过程经常完成,这只是一个重要问题。

无论如何,我在代码中看不到任何可以明显简化的东西……假设当前算法反映了要求。看起来这 6 个循环级别是该问题所固有的。有些计算是这样的。

我能看到的唯一可能性是N带有连接的突触O(N^2)(我认为这就是你正在做的)......在某种程度上是不切实际的。换句话说,只有当我们真正理解您试图使用此代码解决的问题时,我们才能提出重要的改进建议。


请注意,我并不是说“通常,如果某些复杂的东西有效,请不要乱用它。” . 我要说的是:

  • 有些事情本质上无法改进......这看起来像是这样的事情,并且
  • 也许无论如何都无所谓;例如,如果这段代码只执行一次......

“如果它有效,不要惹它”是...... IMO......一个在地毯下刷问题而不给他们适当思考的糟糕借口。

And "Don't bother trying to optimize because usually the extra time and effort produces nothing ..." is simply another formulation of the same excuse. To me, it says "I'm so good that my initial code cannot be improved on" or "I'm so bad that I cannot ever find decent optimizations" or "Too bad ... the customer shouldn't be expecting decent performance anyway".

Note that this is significantly different from the standard (and valid) advice which is ... "Profile before you optimize".

于 2012-11-11T04:09:22.753 回答
0

It all depends on the size of your inputs. The growth rate of these nested loops is not good. I.e., as the size of the inputs grows, the time it takes to run you algorithm will grow much faster, exponentially faster. But if you know your inputs will always be small, then it is fine as it is.

于 2012-11-11T04:14:28.680 回答