http://qs1969.pair.com?node_id=111156

In the section Q&A under Is there a shorter way to create a german time string? I posted some code that's still running in some of my older scripts. Yesterday I got back to the snippet in a printed version and wondered.
I knew I did a benchmark with using localtime and Date::Manip and performance didn't differ significantly for me. Now I still wondered if I could make that code more efficient.
So I tried the following benchmark:
#! /usr/bin/perl -w use strict; use Benchmark qw(timethese); sub zeit_mit_func { # old function calling localtime several times (slightly modified) my $wtag = ("So","Mo","Di","Mi","Do","Fr","Sa")[(localtime)[6]]; my $mtag = sprintf("%02d", (localtime)[3]); my $monat = sprintf("%02d", (localtime)[4]+1); my $jahr = (localtime)[5] + 1900; my $stunde = sprintf("%02d", (localtime)[2]); my $minute = sprintf("%02d", (localtime)[1]); my $zeit = "$wtag $mtag\.$monat\.$jahr - $stunde\:$minute"; return $zeit; } sub zeit_mit_array { # new function calling localtime only once assigning it to an array my @zeit = localtime; my $wtag = ("So","Mo","Di","Mi","Do","Fr","Sa")[$zeit[6]]; my $mtag = sprintf("%02d", $zeit[3]); my $monat = sprintf("%02d", $zeit[4]+1); my $jahr = $zeit[5] + 1900; my $stunde = sprintf("%02d", $zeit[2]); my $minute = sprintf("%02d", $zeit[1]); my $zeit = "$wtag $mtag\.$monat\.$jahr - $stunde\:$minute"; return $zeit; } timethese (1E5, { 'func' => \&zeit_mit_func, 'array' => \&zeit_mit_array, });
The result was (as I had expected)
Benchmark: timing 100000 iterations of array, func... array: 11 wallclock secs (10.82 usr + 0.00 sys = 10.82 CPU) @ 92 +42.14/s (n=100000) func: 33 wallclock secs (32.68 usr + 0.00 sys = 32.68 CPU) @ 30 +59.98/s (n=100000)
on a WinME with ActivePerl Build 628. I also tested it on a FreeBSD 4.0, Perl 5.005 on an old notebook, where the difference was even more significant.

So this is to show - never trust old code. Don't get into the habit of copy and paste.
Make it a habit to review old code, It'll do your code and your coding expertise good.
It already has helped me gain some insights - and I'm sure it'll continue doing so.

neophyte Niederrhein.pm