I've inherited some code at work that does some database updates. Basically does a
$dbh->do() in the middle of a loop. Thousands of times. For testing, I just redirected the Mail output (w/sendmail) to a text file.
#old.pl
while (@emails = $sth->fetchrow) {
$id = $emails[0];
$subject = $emails[1];
$body = $emails[2];
$mailto = $emails[3];
$mailfrom = $emails[4];
$type = $emails[5];
push (@emailsToSend,"To: $mailto\nFrom: $mailfrom\nSubject: $subje
+ct\n\n$body\n");
push (@emailIds,$id);
push (@fromAddys,$mailfrom);
if ($type eq 'weekly') {
$totalweekly++;
}
elsif ($type eq 'daily') {
$totaldaily++;
}
elsif ($type eq 'blast') {
$totalnewsBlast++;
}
elsif ($type eq 'news') {
$totalnews++;
}
}
$emailcount = 0;
foreach $singleEmail (@emailsToSend) {
# SEND THE EMAIL
$mailfrom = $fromAddys[$emailcount];
open (OUT, ">>oldEmail.txt");
print OUT $singleEmail;
close(OUT);
$dbh->do(qq[UPDATE shawnTest set sent = 'Y' WHERE emailId=$emailId
+s[$emailcount]]) ||
&ErrorAlert("500E emailmonitor.pl DBI do error: ".DBI->errstr);
$emailcount++;
}
This seemed like quite a bit of overhead, with the extra variable assignment, as well as the DBI->do, so I did something like this:
#new.pl
my %total=map{$_,0}(qw(weekly daily blast custom));
my $updateSql=qq[UPDATE shawnTest set sent='Y' WHERE emailId=?];
my $update=$dbh->prepare($updateSql);
while(@emails = $sth->fetchrow_array())
{
open (OUT, ">>newEmail.txt");
print OUT "To: $emails[3]\nFrom: $emails[4]\nSubject:$emails[1
+]\n\n$emails[2]\n";
close OUT;
$update->execute($emails[0]);
$total{$emails[5]}++;
}
In both files, this code lives in a sub called fetchemail. I added some code like this to both files.
my $t0 = new Benchmark;
fetchmail();
my $t1 = new Benchmark;
my $td = timediff($t1, $t0);
print "the code took:",timestr($td),"\n";
perl old.pl
the code took: 9 wallclock secs ( 1.43 usr 1.55 sys + 0.02 cusr 0.02 csys = 0.00 CPU)
#Reset database
perl new.pl
the code took: 9 wallclock secs ( 1.59 usr + 1.58 sys = 3.17 CPU)
This code did 10,000 updates, so I didn't feel it necessary to Benchmark it over a thousand times or so. But I did expect, in light of the placeholders, for the results to be a bit more different. Is it my understanding of Benchmark (lack thereof), or do I underestimate the power of placeholders?
ÅßÅ×ÅßÅ
"It is a very mixed blessing to be brought back from the dead." -- Kurt Vonnegut
|