まず、私のひどい英語を申し訳ありません。単位行列の作成でパフォーマンス異常が発生する
私は関数内で恒等行列を動的に作成するための最良の方法を見つけるためのプログラムを書いています。恒等行列を作成する3つの関数があります。最初の関数と2番目の関数はほぼ同じです。それらの違いは次のとおりです。最初の関数の使用memset
配列を0で埋める関数、2番目の関数はこれを組み込みます。最後の関数は、条件文を使用してすべてを1つのループ内でのみ行います。私は条件文を使うと関数が不必要に遅くなると思っていました。コードの
性能比較結果は面白かった、私の推測のすべての逆:
1: 1194
2: 551
3: 440
どのように最後の関数、条件文を使用して、他のすべてよりも高速であることができますか? memset
は長年開発された関数ですが、それはどうして私の組み込みコードよりも遅くなる可能性がありますか?
出典:
#include <stdio.h>
#include <string.h>
#include <time.h>
typedef float MAT4[4][4];
void identityMatrix_1(MAT4 matrix)
{
memset(matrix, 0, sizeof(matrix[0][0]) * 4 * 4);
for(int I = 0; I < 4; I++)
{
matrix[I][I] = 1;
}
}
void identityMatrix_2(MAT4 matrix)
{
for(int X = 0; X < 4; X++)
{
for(int Y = 0; Y < 4; Y++)
{
matrix[X][Y] = 0;
}
}
for(int I = 0; I < 4; I++)
{
matrix[I][I] = 1;
}
}
void identityMatrix_3(MAT4 matrix)
{
for(int X = 0; X < 4; X++)
{
for(int Y = 0; Y < 4; Y++)
{
if(X == Y)
{
matrix[X][Y] = 1;
}
else
{
matrix[X][Y] = 0;
}
}
}
}
void printMAT4(MAT4 matrix)
{
for(int X = 0; X < 4; X++)
{
for(int Y = 0; Y < 4; Y++)
{
printf("%f ",matrix[X][Y]);
}
printf("\n");
}
}
clock_t startTime, endTime;
int main(void) {
MAT4 i1, i2, i3;
startTime = clock();
for(int I = 0; I < 10000; I++)
identityMatrix_1(i1);
endTime = clock();
printf("1: %li \n", endTime - startTime);
startTime = clock();
for(int I = 0; I < 10000; I++)
identityMatrix_2(i2);
endTime = clock();
printf("2: %li \n", endTime - startTime);
startTime = clock();
for(int I = 0; I < 10000; I++)
identityMatrix_3(i3);
endTime = clock();
printf("3: %li \n", endTime - startTime);
//for optimizing the code correctly.
printMAT4(i1);
printMAT4(i2);
printMAT4(i3);
return 0;
}
編集:私はプログラムを最適化しません。
編集:回答に応じてプログラムを編集し、プログラムを最適化しました。
最適化された結果(-O3):
1: 188
2: 0
3: 0
あなたはどのコンパイラを使用していますか? –
コードの最適化をオンにしないと、Usain Boltウォーキングを見ているようです。それほど高速ではなく、非常に面白くない。 –
私はGCCを使用しています。私はそれを最適化する。 –