整页Malloc [英] Full Page Malloc

查看:69
本文介绍了整页Malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过一次使用整个页面来优化程序的内存分配.

I am trying to optimize the memory allocation of my program by using entire pages at a time.

我正在抓取这样的页面大小:sysconf(_SC_PAGESIZE);,然后正在计算将要放入页面的元素总数,例如:elements=pageSize/sizeof(Node);

I am grabbing the page size like this: sysconf(_SC_PAGESIZE); and am then calculating the total number of elements that will fit in a page like this: elements=pageSize/sizeof(Node);

我的想法是,当我实际去分配内存时,我会使用malloc(elements*sizeof(Node));似乎sifeof(Node)的乘法和除法会抵消,但是对于整数除法,我不认为那是案子.

My thinking was that when I actually go to malloc my memory I would use malloc(elements*sizeof(Node)); It seems like the multiplication and division of sifeof(Node) would cancel out, but with integer division, I do not believe that that is the case.

这是一次一次分配整个页面的最佳方法吗?

Is this the best way to malloc an entire page at a time?

谢谢

推荐答案

malloc函数没有页面大小的任何概念.除非您还要分配与页面边界对齐的页面,否则以这种方式调用malloc不会有任何好处.只需malloc所需的任意数量的元素,就不必再担心微优化几乎肯定不会给您带来任何好处的东西了.

The malloc function doesn't have any concept of pagesize. Unless you are allocating pages that are ALSO aligned to a page-boundary, you will not get ANY benefit from calling malloc in this way. Just malloc as many elements as you need, and stop worrying about micro-optimising something that almost certainly won't give you any benefit at all.

是的,Linux内核一直在做这样的事情.这样做有两个原因:

Yes, the Linux kernel does things like this all the time. There are two reasons for that:

  1. 您不希望分配比页面大的​​块,因为这会大大增加分配失败的风险.
  2. 内核分配是按页进行的,而不是像C库那样一次分配大量内存,然后将其拆分为较小的组件.

如果您确实要分配页面大小的内存,请使用sysconf(_SC_PAGESIZE)的结果作为您的大小参数.但是几乎可以肯定,您的分配跨越了两个页面.

If you really want to allocate page-size amount of memory, then use the result from sysconf(_SC_PAGESIZE) as your size argument. But it is almost certain that your allocation straddles two pages.

这篇关于整页Malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆