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

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

用栈上指针 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 倍速度。

 

转载于:https://www.cnblogs.com/luyi07/p/10511491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值