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;
}
전체
왜 unintialized static array가 힙에저장됨 ? bss 아님 ?
니가 어셈블리로바꿔서보심
어레이접근하는거는 컴파일러마다 어셈 ㅈㄴ달라짐 명령어 ㅈㄴ많음 어셈으로봐봐
글로 적은 부분이 죄다 틀려서 어디부터 지적해야할지 모르겠다 퍼포먼스 차이가 난건 캐시 로컬리티 영향인데 지금 그게 중요한게 아니라 컴파일러 옵션이랑 결과로 나온 어셈블리를 좀 봐야할듯 - dc App
static을 힙에 저장한다는건 도데체 뭔 쌉소리인진 모르겠지만 static은 bss에 저장되고, 이런 프로그램에서 스택이 더 빠른 이유는 cpu가 최적화 하기 더 좋은 메모리 영역이라 그럼
스택같은 지역변수는 특정 오프셋이 어느 함수에서 사용되는지 컴파일 타임에 결정되기도 하고 특정 주소범위의 메모리를 자주쓰는 경향이 있는데 cpu가 캐싱을 할때는 read/write 할 주소와 그 주변의 메모리 영역을 다 같이 캐싱하는거 때문에 특정 메모리에 read/write를 많이 수행하는 경우에는 bss보다 스택이 캐싱될 확률이 높음
반면 bss는 특정 메모리를 어디서든 접근할수 있기 때문에 어떤 cpu가 어느 bss에 접근할지 예측하기가 어려움. 그렇다보니 스택에 비해 캐싱될 확률이 낮아지면서 반복적인 접근을 할때 성능이 안나오는거지
하지만 고작 이정도 코드에서는 저 반복문의 어셈이 조금 달라진다고해서 성능에는 그다지 영향없음. 굳이 어셈까지 비교하면서 분석할 필요까진 없는 예제
이딴거 신경 쓰지 마삼 ㅇㅅㅇ 이딴 질문 올리는거 보니까 비전공자 같은데…걍 모른체로 살아라 문제 없당
내가 시발 잘못 아는 줄 알았네 스태틱이 힙에 저장된다고? 뭔 소리지? 했네 ㅋㅋㅋ - dc App
예전에나 메모리 지역성으로 스택이 빠르니 뭐니 했는데 캐시가 존나 커진 현재…. 별 의미 없어짐
현대 컴퓨터는 명령어 실행에 소모되는 cycle보다 메인 메모리에 접근할 때 소모되는 cycle이 압도적으로 비중이 높아 memory gap이라고 검색해보셈