提高阵列的计算处理时间 [英] Improve processing time for array calculation

查看:155
本文介绍了提高阵列的计算处理时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code这个样子
总和+ =阵列[J] +阵列[J + 1] +阵列[J + 2 + ...阵列[J + N];
我该如何更换J + n中的括号内改善的时机?

The code look like this sum += array[j] + array[j+1] + array [j + 2]+ ... array[j + n]; how do I replace the j+n inside the bracket to improve the timing?

推荐答案

您的的做到这一点。除非你有一个脑死亡的编译器,它应该是能够充分地相当优化这个。

You don't do this. Unless you have a brain-dead compiler, it should be able to optimise this quite adequately.

如果你打算做到这个水平微的优化,你需要开始寻找潜在的组装code,的的假设你的编译器会盲目地翻译您的$ C $ ç究竟成等效组装code。

If you're going to do this level of micro-optimisation, you need to start looking at the underlying assembly code, not assuming that your compiler will blindly translate your code into exactly-equivalent assembly code.

您还需要了解你的目标平台的复杂性比写你的编译器是坦白的人好,立足于疯狂code我见过从 GCC 在高优化级别,不太可能: - )

You will also need to understand the intricacies of your target platform better than the people that write your compiler which is frankly, based on the insane code I've seen coming from gcc in high optimisation levels, unlikely :-)

如果你专注于大画面的优化算法一样选择等等,你通常会得到投资回报。

You'll usually get a better return on investment if you concentrate on big-picture optimisations like algorithm selection and so forth.

您的应该怎样的做(如果你还没有的话)是分析的code,一次吃完,看到瓶颈在哪里(和的只有的若它的表现不佳。有一个在优化一个已经运行的速度不够快的东西)是没有意义的。

What you should do (if you haven't already) is profile the code, once finished, to see where the bottlenecks are (and only if it's underperforming: there's no point in optimising something that's already running fast enough).

然后专注于这些瓶颈。的测量,不用猜!

Then concentrate on those bottlenecks. Measure, don't guess!

举例来说,我其实是要告诉你如何优化以下code变成了:

By way of example, I was actually going to show you how well optimised the following code became:

#include <stdio.h>
int main(void) {
    int j, sum, array[50];
    for (j = 0; j < 50; j++)
        array[j] = 999 - j * 2;
    j = 22;
    sum = array[j] + array[j+1] + array [j + 2] + array[j + 3];
    return 0;
}

但在gcc的优化级别3,它变成了:

but under gcc optimisation level 3, it became:

main:
    pushl   %ebp         ; prolog
    xorl    %eax, %eax   ; return value
    movl    %esp, %ebp   ; epilog 1
    popl    %ebp         ; epilog 2
    ret

是的,这是正确的,它只是堆栈序言和结语code和返回值的设定,在视线没有计算。 GCC 已(正确地)想通了,没有计算被用于任何地方,所以已经全面优化出来的存在。

Yes, that's right, it's just the stack prolog and epilog code and setting of the return value, with no calculations in sight. gcc has (rightly) figured out that none of the calculations are used anywhere so has optimised them totally out of existence.

一旦你使用它,相关code变成一个简单的:

Once you use it, the relevant code becomes a simple:

movl    116(%esp), %eax
addl    112(%esp), %eax
addl    120(%esp), %eax
addl    124(%esp), %eax

和你会硬pressed得到它更比进行了优化。

and you'd be hard-pressed getting it much more optimised than that.

这篇关于提高阵列的计算处理时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆