void sub(){
int stack_dynamic1[A][A];
int stack_dynamic2[A][A];
int stack_dynamic3[A][A];
static int static_local1[A][A];
static int static_local2[A][A];
static int static_local3[A][A]; ...
이렇게 정의하면 stack_배열은 스택에저장, static_배열은 힙에저장되잖아요
이떄 각 배열에 접근할 때 스택은 SP레지스터 읽어서 offset만큼 덧셈 op 한번에 주소계산,
static은 GP + offset해서 한번에 주소 계산하기때문에
두 방법을 사용했을 때 시간이 같아야 정상 아닌가요
왜 스택이 빠를까요 혹시 놓친 부분이 있을까요
전체 코드 입니다
#include <iostream>
#include <random>
#include <ctime>
#define A 200
void sub(){
int stack_dynamic1[A][A];
int stack_dynamic2[A][A];
int stack_dynamic3[A][A];
static int static_local1[A][A];
static int static_local2[A][A];
static int static_local3[A][A];
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(1, 100);
for(int i = 0; i<A; i++){
for(int j = 0; j<A; j++){
stack_dynamic1[i][j] = dist(gen); //stack
stack_dynamic2[i][j] = dist(gen); //stack
stack_dynamic3[i][j] = 0;
}
}
for(int i = 0; i<A; i++){
for(int j = 0; j<A; j++){
static_local1[i][j] = dist(gen); //static
static_local2[i][j] = dist(gen); //static
static_local3[i][j] = 0;
}
}
clock_t start;
clock_t end;
start = clock();
for(int re = 0; re < A; re++){
for(int a = 0; a<A; a++){
for(int b = 0; b<A; b++){
for(int i = 0; i<A; i++){
stack_dynamic3[a][b] += stack_dynamic1[a][i]*stack_dynamic2[i][b];
}
}
}
}
end = clock();
std::cout << "Stack-dynamic matrix multiply time: " << (double)(end - start) / CLOCKS_PER_SEC << " seconds" << std::endl;
start = clock();
for(int re = 0; re<A; re++){
for(int a = 0; a<A; a++){
for(int b = 0; b<A; b++){
for(int i = 0; i<A; i++){
static_local3[a][b] += static_local1[a][i]*static_local2[i][b];
}
}
}
}
end = clock();
std::cout << "Static matrix multiply time: " << (double)(end - start) / CLOCKS_PER_SEC << " seconds" << std::endl;
}
int main(void){
sub();
return 0;
}
전체
이것만봐도 모름 이건 코드 문제가 아니라, 그냥 CS 구조 무제라서
이론상 니 말이 맞는데, 캐시 친화적이냐 아니냐도 문제가 있고. 기본적으로 컴파일러까지 겹친 문제라 결국 스택이 더 캐시 친화적이기때문에 더 빠르다라고 하는게 맞음.
이론적으론 스택이 캐시친화적이라 빠르다고 생각하면 되겟군요 감사합니다
근데 캐시는 특정 접근하는 데이터를 저장하는데 왜 데이터영역이랑 스택영역이랑 차등을 두는 건가여 그냥 접근하면 캐시에 올라가는거 아닌가요?
@글쓴 프갤러(210.104) 내 기억으론 현대 컴파일러 구조가 스택에 맞게 되서 그런걸로 앎. 실제론 이론이랑 실제 컴파일러, 캐시계층등등 복잡해서 실제 이론대로 다 안돌아감
@글쓴 프갤러(210.104) 이건 캐시히트 구조에서 스택이 더 유리해서일거임
@글쓴 프갤러(210.104) 아, 이거 기억이 존나 가물해서 스택이랑 데이터 영역 차등 두는 이유가 캐시 예측 가능성때문이라고 알긴하는데 자세한건 기억이 안난다 미안하다
잉 static 변수가 힙이라고?
아 데이터영역이요