Alois Mahdal
Alois Mahdal

Reputation: 11253

Deliberately eating certain amount of memory using perl script

I need to simulate a memory-hungry process. For example, On a machine with 4.0 GiB, I need a process that would eat 3.2 GiB (give or take few MiB).

I assumed it should be as easy as:

my $mbytes = 3276;
my $huge_string = 'X' x ($mbytes * 1024 * 1024);

But I end up with process eating twice as much memory as I need it to.

Of course, I could just $mbytes /= 2 (for now, I'll probably will do that), but:

Upvotes: 3

Views: 1753

Answers (1)

daxim
daxim

Reputation: 39158

Code adapted from http://www.perlmonks.org/index.pl?node_id=948181, all credit goes to Perlmonk BrowserUk.

my $huge_string = 'X';
$huge_string x= $mbytes * 1024 * 1024;

why the amount is twice as length of the string?

Think about the order of evaluation. The right-hand expression allocates memory for your x expression, and again so does the assignment operation into your new scalar. As usual for Perl, even though the right-hand expression is not referenced anymore, the memory is not freed right away.

Operating on an existing scalar avoids the second allocation, as shown above.

Upvotes: 6

Related Questions