我有以下结构:
struct Matrix
{
int numOfRows;
int numOfColumns;
double* values;
int* permutationVector;
}
我还有以下功能:
void SetRowToZero(Matrix* m, int row)
{
int rowBegin = row*(m->numOfColumns);
for (int c = 0; c < (m->numOfColumns); c++)
{
m->values[rowBegin + c] = 0;
}
}
我想知道在运行期间有没有性能下降?
如果我这样写函数有什么区别吗:
void SetRowToZero(Matrix* m, int row)
{
// Unpacking structure
int numOfColumns = m->numOfColumns;
double* values = m->values;
int rowBegin = row*(m->numOfColumns);
for (int c = 0; c < numOfColumns; c++)
{
values[rowBegin + c] = 0;
}
}
总的来说,我是否应该关心在如此小的范围内表演?
最佳答案
编译器优化将导致两段代码都被优化为使用该值的寄存器。
我在x86_64上测试了这个小程序,并使用gcc 5.4进行了4级优化
#include <stdlib.h>
struct Matrix
{
int numOfRows;
int numOfColumns;
double* values;
int* permutationVector;
};
void SetRowToZero1(struct Matrix* m, int row)
{
int rowBegin = row*(m->numOfColumns);
for (int c = 0; c < (m->numOfColumns); c++)
{
m->values[rowBegin + c] = 0;
}
}
void SetRowToZero2(struct Matrix* m, int row)
{
// Unpacking structure
int numOfColumns = m->numOfColumns;
double* values = m->values;
int rowBegin = row*(m->numOfColumns);
for (int c = 0; c < numOfColumns; c++)
{
values[rowBegin + c] = 0;
}
}
int main() {
struct Matrix matrix = {5,1000000, malloc(5 * 1000000 * sizeof(double)), NULL};
SetRowToZero1(&matrix, 1);
}
我编的:
gcc -O4 main.c -o test1.out
然后我改变了
SetRowToZero1(&matrix, 1);
到
SetRowToZero2(&matrix, 1);
编制:
gcc -O4 main.c -o test2.out
然后:
$md5sum test1.out测试2.out
504fb75e97173a6864750f5feb7cea58测试12.out
504fb75e97173a6864750f5feb7cea58测试1.out
所以您可以肯定地说,实现没有区别:)