Coding/CPP 삽질기2021. 2. 25. 23:52

1. Stack과 Heap 영역에 변수 생성 시간 테스트

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_COUNT 1000000


void do_nothing_test() {
    clock_t start = clock();

    for (int i = 0; i < MAX_COUNT; i++)
    ;

    printf("Empty: %f\n", ((float)(clock()-start)/CLOCKS_PER_SEC));
}


void stack_create_test() {
    clock_t start = clock();

    for (int i = 0; i < MAX_COUNT; i++) {
        int arr[10] = { 0, };
    }

    printf("Stack: %f\n", ((float)(clock()-start)/CLOCKS_PER_SEC));
}


void heap_create_test() {
    clock_t start = clock();

    for (int i = 0; i < MAX_COUNT; i++) {
        int *arr = malloc(sizeof(int)*10);
        free(arr);
    }

    printf("Heap:  %f\n", ((float)(clock()-start)/CLOCKS_PER_SEC));
}

int main(int argc, char **argv) {
    do_nothing_test();
    stack_create_test();
    heap_create_test();
    return 0;
}

결과

chobocho@Chobocho-Mint:~/github/cpp_study/src/memory$ ./a.out
Empty: 0.003636
Stack: 0.003976
Heap:  0.015938

'Coding > CPP 삽질기' 카테고리의 다른 글

별 그리기  (0) 2021.06.08
[C] Binary search  (0) 2020.12.06
Quick sort  (0) 2017.07.13
Posted by chobocho