zoukankan      html  css  js  c++  java
  • 开辟栈内存速度 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 倍速度。

  • 相关阅读:
    react-native 安卓支持 gif动态图
    react-navigation,StackNavigator,TabNavigator 导航使用
    poj3694 网络(板子题)
    POJ1275 Cashier Employment 差分约束(优化 二分)
    Codeforces Round #667 (Div. 3)
    POJ1201 Intervals 差分约束(贪心也可)
    YY的GCD
    Codeforces Round #666 (Div. 2) A~E
    Rendezvous
    创世纪
  • 原文地址:https://www.cnblogs.com/luyi07/p/10511491.html
Copyright © 2011-2022 走看看