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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With