Coding Practices which enable the compiler/optimizer to make a faster program

后端 未结 30 1935
一个人的身影
一个人的身影 2020-12-02 03:24

Many years ago, C compilers were not particularly smart. As a workaround K&R invented the register keyword, to hint to the compiler, that maybe it woul

30条回答
  •  悲哀的现实
    2020-12-02 04:13

    The order you traverse memory can have profound impacts on performance and compilers aren't really good at figuring that out and fixing it. You have to be conscientious of cache locality concerns when you write code if you care about performance. For example two-dimensional arrays in C are allocated in row-major format. Traversing arrays in column major format will tend to make you have more cache misses and make your program more memory bound than processor bound:

    #define N 1000000;
    int matrix[N][N] = { ... };
    
    //awesomely fast
    long sum = 0;
    for(int i = 0; i < N; i++){
      for(int j = 0; j < N; j++){
        sum += matrix[i][j];
      }
    }
    
    //painfully slow
    long sum = 0;
    for(int i = 0; i < N; i++){
      for(int j = 0; j < N; j++){
        sum += matrix[j][i];
      }
    }
    

提交回复
热议问题