Ami*_*deh 10 c c++ compiler-construction optimization compiler-optimization
当我回答另一个人的问题时,我遇到了这个问题.编译器如何优化代码?const,...等关键字可以帮忙吗?除了挥发性和内联函数以及如何通过自己优化代码之外的事实!
您可以做的一件非常重要的事情(超出编译器可以为您做的事情)是要了解缓存.由于访问内存非常耗时,因此缓存会尝试不仅存储您访问它的数据,还会存储附近的元素.这就是为什么foo跑得比以前快得多bar:
array[ NUM_ROWS ][ NUM_COLS ];
foo()
{
int row, col;
int sum = 0;
// accesses the elements in the array continuously
for ( row = 0; row < NUM_ROWS ; row++ )
{
for ( col = 0; col < NUM_COLS; col++ )
{
sum += array[ row ][ col ];
}
}
}
bar()
{
int row, col;
int sum = 0;
// skips from row to row ( big jumps that might miss the cache )
for ( col = 0; col < NUM_COLS ; col++ )
{
for ( row = 0; row < NUM_ROWS; row++ )
{
sum += array[ row ][ col ];
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
要注意的另一件事是重复字符串连接.做错了,这可以使代码看起来O( n )实际上在其中运行O( n^2 )- 请参阅有关Joel on Software的文章
编辑: s/disk/memory /