6

我曾尝试使用限制限定指针,但遇到了问题。下面的程序只是一个简单的程序,仅用于提出问题。

calc_function 使用三个指针,这是受限制的,因此它们“应”不相互别名。在 Visual Studio 中编译此代码时,该函数将被内联,因此 Visual Studio 2010 无缘无故忽略限定符。如果我禁用内联,代码的执行速度会快六倍(从 2200 毫秒到 360 毫秒)。但我不想在整个项目或整个文件中禁用内联(因为那样会在所有 getter 和 setter 中调用开销,这将是可怕的)。

(可能唯一的解决方案是仅禁用此函数的内联吗?)

我试图在函数中创建临时限制限定指针,在顶部和内部循环中试图告诉编译器我保证没有别名,但编译器不会相信我,它不会工作。我也尝试过调整编译器设置,但我发现唯一可行的是禁用内联。

我会很感激一些帮助来解决这个优化问题。

要运行程序(在 realease 模式下)不要忘记使用参数 0 1000 2000。为什么使用用户输入/程序参数是为了确保编译器无法知道指针之间是否存在别名a、b 和 c。

#include <cstdlib>
#include <cstdio>
#include <ctime>

// Data-table where a,b,c will point into, so the compiler cant know if they alias.
const size_t listSize = 10000;
int data[listSize];

//void calc_function(int * a, int * b, int * c){
void calc_function(int *__restrict a, int *__restrict b, int *__restrict c){
    for(size_t y=0; y<1000*1000; ++y){  // <- Extra loop to be able to messure the time.
        for(size_t i=0; i<1000; ++i){
            *a += *b;
            *c += *a;
        }
    }
}
int main(int argc, char *argv[]){ // argv SHALL be "0 1000 2000" (with no quotes)
    // init
    for(size_t i=0; i<listSize; ++i)
        data[i] = i;

    // get a, b and c from argv(0,1000,2000)
    int *a,*b,*c;
    sscanf(argv[1],"%d",&a);
    sscanf(argv[2],"%d",&b);
    sscanf(argv[3],"%d",&c);
    a = data + int(a);  // a, b and c will (after the specified argv) be,
    b = data + int(b);  // a = &data[0], b = &data[1000], c = &data[2000],
    c = data + int(c);  // So they will not alias, and the compiler cant know.

    // calculate and take time
    time_t start = clock();
        funcResticted(a,b,c);
    time_t end = clock();
    time_t t = (end-start);
    printf("funcResticted       %u (microSec)\n", t);

    system("PAUSE");
    return EXIT_SUCCESS;
}
4

1 回答 1

3

如果你用 声明一个函数__declspec(noinline),它将强制它不被内联:

http://msdn.microsoft.com/en-us/library/kxybs02x%28v=vs.80%29.aspx

您可以使用它在每个函数的基础上手动禁用内联。


至于restrict,编译器只有在需要时才可以自由使用。因此,当试图“欺骗”编译器进行此类优化时,摆弄相同代码的不同版本在某种程度上是不可避免的。

于 2012-07-15T20:43:20.853 回答