use strict; use warnings; my $DB = "test"; my $USER = "dbusername"; my $PASS = "dbpassword"; my $DEBUG = 0; my $BENCHMARK_LOOP_LIMIT = 10_000; my $EXPIRATION_TIME = 60; use Data::Dumper; use DBI; my $dbh = DBI->connect("dbi:mysql:$DB", $USER, $PASS, {RaiseError => 1}) || die "Cannot connect to db"; ### Prepare caches use Cache::FileCache; my $fc = Cache::FileCache->new({default_expires_in => $EXPIRATION_TIME}); $fc->Clear; use Cache::MemoryCache; my $mc = Cache::MemoryCache->new({default_expires_in => $EXPIRATION_TIME}); $mc->Clear; # Superfluous my %cache; my $flush_interval = 10; my $flush_time = time + $flush_interval; use Benchmark qw( timethese cmpthese ); my $results = timethese ($BENCHMARK_LOOP_LIMIT, { raw => sub {my $r = raw_load_from_cachetest(5000 + int(rand(30)));}, FileCache => sub {my $r = fc_load_from_cachetest(5000 + int(rand(30)));}, MemoryCache => sub {my $r = mc_load_from_cachetest(5000 + int(rand(30)));}, SimpleCache => sub {my $r = sc_load_from_cachetest(5000 + int(rand(30)));}, }, ); cmpthese($results); # Load straight from database sub raw_load_from_cachetest { my ($id) = @_; my $sql = qq[select * from cachetest where id=?]; my $sth = $dbh->prepare($sql); $sth->execute($id); my $result = $sth->fetchrow_hashref || return; return $result; } # Cached load using Cache::FileCache sub fc_load_from_cachetest { my ($id) = @_; my $result; my $key = "cachetest$id"; $result = $fc->get($key) || do { $result = raw_load_from_cachetest($id); $fc->set($key, $result); $result }; return $result; } # Cached load using Cache::MemoryCache sub mc_load_from_cachetest { my ($id) = @_; my $result; my $key = "cachetest$id"; $result = $mc->get($key) || do { $result = raw_load_from_cachetest($id); $mc->set($key, $result); $result }; return $result; }; # Cached load using simple cache found at: sub sc_load_from_cachetest { my ($id) = @_; ($flush_time, %cache) = time + $flush_interval if $flush_time < time; $cache{$id} ||= raw_load_from_cachetest($id); } #### use strict; use warnings; ### Begin configuration my $DSN = "dbi:mysql:test"; my $USER = "dbusername"; my $PASS = "dbpassword"; ### End configuration use DBI; my $dbh = DBI->connect($DSN, $USER, $PASS, {RaiseError => 1}) || die "Cannot connect to db"; $dbh->do(qq[delete from cachetest]); for(my $i=1;$i<=20000; $i++) { $dbh->do(qq[insert into cachetest (a,b,c,d,e,f,g) values (?,?,?,?,?,?,?)], undef, rand(1_000_000), rand(1_000_000), rand(1_000_000), rand(1_000_000), rand(1_000_000), rand(1_000_000), rand(1_000_000), );