http://www.perlmonks.org?node_id=1041613

not_japh has asked for the wisdom of the Perl Monks concerning the following question:

I had a particular need for a fast mktime. Search foo lacking, I wrote a naive implementation (below) which seems to work very well, for me at least.

The use case is parsing logfile timestamps from ctime()-ish format into time_t epoch integer. The simplifying assumption is that once you've used a smart date parser to parse one timestamp, the next one you parse can be done much faster by looking only at the previous $time result and the new H:M:S, as long as both stamps lie within the same day. Fortunately, giant logfiles are often conveniently arranged in order so that this is usually true.

The hypothesis appears confirmed by some benchmarking of 1e7 (sequential!) dates:

# POSIX::mktime took: 139 wallclock secs (33.27 usr + + 40.64 sys = 73.91 CPU) # Time::Local::timegm_nocheck took: 58 wallclock secs (57.67 usr + + 0.15 sys = 57.82 CPU) # FastMktime took: 22 wallclock secs (22.53 usr + + 0.02 sys = 22.55 CPU)
Any thoughts appreciated. Should this be cpanned, or round-canned?
#!/usr/bin/perl # Drop-in POSIX::mktime() replacement. This is optimized for repeated # calls within the same date by caching previous result: if the cache # applies, it just performs the H:M:S calculation within the same day, # if not it falls through to POSIX::mktime() and stores the result for # next invocation. use strict; use warnings; use POSIX qw(mktime); package FastMktime; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(caching_mktime); my $mk_day = 0; my $mk_mon = 0; my $mk_year = 0; my $mk_time = 0; my $mk_hms = 0; sub caching_mktime { my ($s, $m, $h, $day, $mon, $year) = @_; my $time; my $hmsarg = 3600 * $h + 60 * $m + $s; if ($mk_day > 0 && $mk_day == $day && $mk_mon == $mon && $mk_year == + $year) { $time = $mk_time + $hmsarg - $mk_hms; } else { $time = POSIX::mktime($s, $m, $h, $day, $mon, $year); $mk_day = $day; $mk_mon = $mon; $mk_year = $year; $mk_time = $time; $mk_hms = $hmsarg; } return $time; } 1;