Intentionally using a certain amount of memory using a perl script

I need to simulate a hungry process. For example, on a 4.0 GiB machine, I need a process that will consume 3.2 gigabytes (give or take some MiB).

I assumed it should be that simple:

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

      

But in the end, I end up with twice as much memory as I need.

  • it's the same on two windows 7 amd64 computers, one with 64-bit, the other with 32-bit Strawberry Perl build

  • I am using Sysinternals Process Explorer and looking at "Private Bytes"

Of course, I could have just $mbytes /= 2

(at the moment I will probably do this), but:

  • Is there a better way?

  • Can anyone explain why the sum is twice the length of the string?

+3


source to share


1 answer


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 is the sum twice the length of the string?

Think about the evaluation order. The correct expression allocates memory for your expression x

, and again the assignment operation to your new scalar. As usual for Perl, although the right-hand expression is no longer mentioned, the memory is not immediately freed.

Working on the existing scalar avoids the second selection as shown above.

+6


source







All Articles