Neo
Neo

Reputation: 3735

How to write a simple "page fault generator"?

For my course project on Linux Kernel, I need to simulate a situation where there is a lot of page swapping due to low memory.

I want to write a program which needs a lot of physical memory, so that pages accessed by this program have to be swapped in and out multiple times.

Upvotes: 6

Views: 2986

Answers (2)

VAndrei
VAndrei

Reputation: 5600

Of, so first of all you really need to allocate a buffer larger than your RAM size. I hope you run on a 64bit OS or you have PAE enabled. If have let's say 4GB of RAM, you need something like:

double* pBigArray = (double*)malloc(sizeof(double) * 536870912); 
// You actually need more than that. This is just 4GB.

Now, just having an array, larger than your RAM size is not enough. It matters how you access it. If you just read elements consecutively, the hardware prefetchers in your CPU will bring some of the data your program will read, into the cache.

To generate many page faults, you need to read from an address that is not in the RAM.

To do that this is a simple method, by reading from the array randomly:

double lfBigChecksum = 0.0;
while (true)
{
   int iIndex = rand() % BUFFER_SIZE;
   lfBigChecksum += pBigArray[iIndex];
}

If you have an array of 8GB and 4GB of RAM, half of the reads will be page faults (and served from the swap space in the hard disk).

Upvotes: 5

You can eat up a ton of memory just by dynamically allocating tons of space and not using it. IE in C++ you can do

int *foo = new int[10000000];

Which will just eat up 40MB (assuming your ints are 4 btyes) and do nothing with it. Do this a couple of times (you may need to spread it out over several processes) and you'll eat up your RAM fast.

Upvotes: -3

Related Questions