Showing posts with label perl5. Show all posts
Showing posts with label perl5. Show all posts

Thursday, February 11, 2010

inverting a hash

Code I've written in the past to swap keys and values

my %hash = ( foo => bar, ... fee=>fo);
my %reversed_hash;
foreach my $key (keys %hash) {
$reversed_hash{$hash{$key}} = $key;
}


or... I could have just done this all along.
%hash = reverse %hash;


When you think of how this works by treating the hash as an array of key/value pairs then just reversing the order of the array, it initially feels somehow "dirty". But give it a few minutes and you realize it's really a frickin elegant solution!

Friday, July 3, 2009

How to kill your system by allocating all memory in perl

Sometimes you want to see how things behave on a host when it runs out of memory

We actually caused a linux host with 128GB RAM to hang until we pulled the plug by doing this.

To allocate more memory, change $procs to a bigger number. If you have 64bit perl, you can kill the host with 1 process, just concatenating strings with the subroutine below.


#!perl
use forks;

my $procs = 2;
for (1..$procs) {
print "Forking: " . `date`;
threads->new(\&mem_load);
}
print "sleeping: " . `date`;
sleep 10;


sub mem_load {
my $str = "0123456789abcdef" x 1024;
$str = $str x 1024;

my $mem = $str;
for (1..130) {
$mem .= $str;
print "$$: $_\n";
}
sleep 9999999;
}

How to create high CPU load in perl

Sometimes you need to test how a host behaves when it's bogged down.

This code is fairly safe. Change $procs to a big number if you want to see it kill your host.


#!perl
use forks;

my $procs = 2;
for (1..$procs) {
threads->new(\&fpu_load);
threads->new(\&cpu_load);
}
sleep 100;

sub fpu_load {
my ($f1, $f2, $sum);
while(1) {
$f1 = rand(1000);
$f2 = rand(1000);
$sum = $f1 * $f2;
}
}

sub cpu_load {
my ($f1, $f2, $sum);
while(1) {
$f1 = rand(1000);
$f2 = rand(1000);
$sum = $f1 * $f2;
}
}