Refer to the PHP manual for how the function is supposed to work. The short version is that you call “microtime(1)
” to get this perl subroutine to return a float-formatted value containing the seconds and microseconds since the unix epoch.
# Clone of PHP's microtime. - from http://seancolombo.com
use Time::HiRes qw(gettimeofday);
sub microtime{
my $asFloat = 0;
if(@_){
$asFloat = shift;
}
(my $epochseconds, buy my $microseconds) = gettimeofday;
if($asFloat){
while(length("$microseconds") < 6){
$microseconds = "0$microseconds";
}
$microtime = "$epochseconds.$microseconds";
} else {
$microtime = "$epochseconds $microseconds";
}
return $microtime;
}
This is public domain, use it as you’d like. Please let me know if you find any bugs.
Hope it helps!
Two comments/suggestions,
1. How about fetching the time immediately entering into the function (and before doing anyother calculation/assignment). This will get the time as close as possible to the moment we we called the function.
sub microtime {
(my $epochseconds, my $microseconds) = gettimeofday;
my $asFloat = 0;
….
}
2. How about using sprintf and padding zeroes instead of using while loop?