简体   繁体   English

为什么 memory 管理器使用 (size + PAGE_SIZE-1) / PAGE_SIZE 来计算要分配的页数?

[英]Why do memory managers use (size + PAGE_SIZE-1) / PAGE_SIZE to calculate the number of pages to allocate?

I have met such a formula multiple times in various places (eg; Linux kernel and glibc).我在不同的地方多次遇到过这样的公式(例如;Linux kernel 和 glibc)。 Why do they use this formula instead of simply:为什么他们使用这个公式而不是简单地:

pages = (size / PAGE_SIZE) + 1;

As a guess, I think the problem with the formula above is when the size is PAGE_SIZE aligned (a multiple of PAGE_SIZE ) because, in such a case, it reports one more page than needed, thus we have to also do:作为一种猜测,我认为上面公式的问题是当大小是PAGE_SIZE对齐时( PAGE_SIZE的倍数),因为在这种情况下,它报告的页面比需要的多,因此我们还必须这样做:

pages = (size / PAGE_SIZE) + 1;
if (!(size & (PAGE_SIZE-1))) /* is size a multiple of PAGE_SIZE? */
    pages--;

which is obviously more code than just (size + PAGE_SIZE-1) / PAGE_SIZE !这显然比(size + PAGE_SIZE-1) / PAGE_SIZE更多的代码!

Yes, it's used to get the ceiling of the division result, ie rounding the quotient up是的,它用于获取除法结果的上限,即四舍五入的商

The problem with问题与

pages = (size / PAGE_SIZE) + 1;
if (!(size & (PAGE_SIZE-1))) /* is size a multiple of PAGE_SIZE? */
    pages--;

is not only a lot more code but also the fact that不仅是更多的代码,而且事实上

  • it has worse performance due to the branch由于分支,它的性能更差
  • it only works for powers of 2它仅适用于 2 的幂

Of course page size in a binary computer is always a power of 2, but (size + PAGE_SIZE-1) / PAGE_SIZE works for any value of the divisor当然,二进制计算机中的页面大小始终是 2 的幂,但是(size + PAGE_SIZE-1) / PAGE_SIZE适用于除数的任何值

See also也可以看看

This is rounding up.这是四舍五入。 You add (PAGE_SIZE - 1) to nbytes so in case you have an exact number of PAGE_SIZE nbytes then you get the minimum number of pages you need, and if you pass it by one, then you get a new page to give space for the extra byte.您将(PAGE_SIZE - 1)添加到nbytes ,因此如果您有确切数量的PAGE_SIZE nbytes ,那么您将获得所需的最小页面数,如果您将其传递一个,那么您将获得一个新页面,以便为额外的字节。

There is another way to make it with the log2 of the page size.还有另一种方法可以使用页面大小的log2 In the Linux kernel source, it is PAGE_SHIFT .在 Linux kernel 源中,它是PAGE_SHIFT For example, if PAGE_SIZE is 4096 = 2^12 bytes, PAGE_SHIFT is 12 (ie log2(2^12)).例如,如果PAGE_SIZE为 4096 = 2^12 字节,则 PAGE_SHIFT为 12(即 log2(2^12))。 So, to get the number of pages for a given size , the following formula is often used:因此,要获得给定size页数,通常使用以下公式:

pages = ( size + PAGE_SIZE - 1) >> PAGE_SHIFT页数= (大小+ PAGE_SIZE - 1) >> PAGE_SHIFT

By the way, the page size is often defined as:顺便说一句,页面大小通常定义为:

#define PAGE_SIZE (1 << PAGE_SHIFT ) #define PAGE_SIZE (1 << PAGE_SHIFT )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM