关于系统参数:vm.overcommit_memory 和 vm.overcommit_ratio;

本文详细探讨了Linux系统中与内存管理相关的两个关键参数vm.overcommit_memory和vm.overcommit_ratio。vm.overcommit_memory设定内存分配策略,其值为0时严格检查内存,值为1时不进行检查,值为2时限制单次分配。vm.overcommit_ratio在vm.overcommit_memory设为2时生效,用于计算系统可用内存。通过不同设置组合的测试,展示了它们如何影响最大可分配内存大小。

overcomit_memory

    0 :用户申请内存的时候,系统会判断剩余的内存多少,如果不够的话那么就会失败。

    1:  用户申请内存的时候,系统不进行任何检查任务内存足够用,直到使用内存超过可用内存。

    2: 用户一次申请的内存大小不允许超过可用内存的大小。

overcommit_ratio

    overcomit_memory= 2时,该参数有效,这个参数决定了系统可用内存的大小。

    计算公式: (Physical-RAM-Size*ratio / 100 +(Swap-Size) 

                       (Physical-RAM-Size)= Men 行的 total :5792

                         ratiao = 99 (仅当 overcomit_memory =2)

                         (Swap-Size) = Swap 行的 total : 1983

                   得: (5792*99/100)+  1983 = 7123M

本机当前内存使用情况

[root@localhost /]# free -m (M为 单位)
             total       used       free     shared    buffers     cached
Mem:          5792        513       5279          0         40        158
-/+ buffers/cache:        314       5478
Swap:         1983          0       1983
[root@localhost /]#

测试代码:

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

size_t max_num = 0;
int main(int argc, char **argv)
{
        void *block;
        void *tmp_block;
        size_t block_size[] = {1024*1024, 1024, 1};
        int i=0;
        int count;

        for(i=0; i<3; i++)
        {
                for(count = 1; ;count ++)
                {
                        block = malloc(max_num + block_size[i]*count);
                        if(block)
                        {
                                tmp_block = block;
                                max_num += block_size[i]*count;
                                printf("max_num current malloc size =%lf GB\n",max_num*1.0/1024.0/1024.0/1024.0);
                                free(block);
                        }
                        else
                        {
                                break;
                        }
                }
        }
        printf("max_num malloc size = %lf GB\n", max_num*1.0/1024.0/1024.0/1024.0);
        printf("the address is %x \n",tmp_block);
        printf("the address end is %x\n", tmp_block + max_num);
        while(1);
}


 

情况 ①

overcomot_memory = 0vm.overcommit_ratio = 50 =》max_num malloc size = 7.137890GB

 

情况②

overcomot_memory = 2 vm.overcommit_ratio = 50 =》max_num malloc size = 3.958923GB

 

情况③

overcomot_memory = 2 vm.overcommit_ratio = 99 =》 max_nummalloc size = 6.722099 GB

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值