首页 > 其他 > 详细

开辟栈内存速度 v.s. 开辟堆内存速度

时间:2019-03-11 16:49:21      阅读:215      评论:0      收藏:0      [点我收藏+]

在函数内直接定义多维数组,即可在栈上开辟内存。

用栈上指针 new 出堆内存,定义多维数组,即在堆上开辟内存。

可以比较这两种的速度,做个小实验,心里有个数。

代码如下:

#include<iostream>
using namespace std;

#include<cmath>
#include<time.h>

#define n 1000

void open_stack_memory(){
    int a[n][n];
}

void open_heap_memory(){
    int **a = new int *[n];
    for(int i=0;i<n;i++)
        a[i] = new int [n];
    for(int i=0;i<n;i++)
        delete [] a[i];
    delete [] a;
}

int main(){

    int repeat1 = 1E7;

    clock_t t_start = clock();
    for(int i=0;i<repeat1;i++)
        open_stack_memory();
    clock_t t_end = clock();
    cout<<" It took me "<<(double)(t_end - t_start)/CLOCKS_PER_SEC<<" s to open stack memory "<<repeat1<<" times repeatedly"<<endl;

    int repeat2 = 1E1;
    t_start = clock();
    for(int i=0;i<repeat2;i++)
        open_heap_memory();
    t_end = clock();
    cout<<" It took me "<<(double)(t_end - t_start)/CLOCKS_PER_SEC<<" s to open  and delete heap memory "<<repeat2<<" times repeatedly"<<endl;

    return 0;
}

运行结果为:

 It took me 0.03125 s to open stack memory 10000000 times repeatedly
 It took me 0.0625 s to open  and delete heap memory 10 times repeatedly

所以,直接征用栈内存,是 new 出堆内存的 1E6 倍速度。

 

开辟栈内存速度 v.s. 开辟堆内存速度

原文:https://www.cnblogs.com/luyi07/p/10511491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!