for 구문 사용시, 인덱싱하는 order 에 따라, 실행시간에 차이가 발생한다는 글을 보았다(참조: http://process3.blog.me/20030421397)
정말로 그럴까? 한번 확인해 보았다. 결론은? 확실한 차이가 있었다.
이유를 확인해보니, 메모리 캐시와 관련된 내용이었다.
— Program 1
#include <stdio.h>
#define MAX_CNT 100
int main(int argc, char** argv)
{
int i, j, k;
int test_data[MAX_CNT][MAX_CNT][MAX_CNT];
for(i = 0; i < MAX_CNT; i++)
{
for(j = 0; j < MAX_CNT; j++)
{
for(k = 0; k < MAX_CNT; k++)
{
test_data[i][j][k] = 100;
}
}
}
return 0;
}
Result
$ time ./main
real 0m0.008s
user 0m0.004s
sys 0m0.004s
— Program 2
#include <stdio.h>
#define MAX_CNT 100
int main(int argc, char** argv)
{
int i, j, k;
int test_data[MAX_CNT][MAX_CNT][MAX_CNT];
for(i = 0; i < MAX_CNT; i++)
{
for(j = 0; j < MAX_CNT; j++)
{
for(k = 0; k < MAX_CNT; k++)
{
test_data[k][j][i] = 100;
}
}
}
return 0;
}
$ time ./main
real 0m0.017s
user 0m0.013s
sys 0m0.004s
힙 영역 사용시, 보다 더 큰 차이를 확인할 수 있다.
— Program 1
#include <stdio.h>
#include <stdlib.h>
#define MAX_CNT 500
int main(int argc, char** argv)
{
int i, j, k;
// int test_data[MAX_CNT][MAX_CNT][MAX_CNT];
int*** test_data;
test_data = calloc(MAX_CNT, sizeof(int**));
for(i = 0; i < MAX_CNT; i++)
{
test_data[i] = calloc(MAX_CNT, sizeof(int*));
for(j = 0; j < MAX_CNT; j++)
{
test_data[i][j] = calloc(MAX_CNT, sizeof(int));
}
}
for(i = 0; i < MAX_CNT; i++)
{
for(j = 0; j < MAX_CNT; j++)
{
for(k = 0; k < MAX_CNT; k++)
{
test_data[i][j][k] = 100;
}
}
}
return 0;
}
Result
$ time ./main
real 0m0.539s
user 0m0.367s
sys 0m0.172s
— Program 2
#include <stdio.h>
#include <stdlib.h>
#define MAX_CNT 500
int main(int argc, char** argv)
{
int i, j, k;
// int test_data[MAX_CNT][MAX_CNT][MAX_CNT];
int*** test_data;
test_data = calloc(MAX_CNT, sizeof(int**));
for(i = 0; i < MAX_CNT; i++)
{
test_data[i] = calloc(MAX_CNT, sizeof(int*));
for(j = 0; j < MAX_CNT; j++)
{
test_data[i][j] = calloc(MAX_CNT, sizeof(int));
}
}
for(i = 0; i < MAX_CNT; i++)
{
for(j = 0; j < MAX_CNT; j++)
{
for(k = 0; k < MAX_CNT; k++)
{
test_data[k][j][i] = 100;
}
}
}
return 0;
}
Result
$ time ./main
real 0m5.344s
user 0m5.202s
sys 0m0.147s