Perl: Stopwatch with millisecond level accuracy

I need a quick way to measure milliseconds of duration in a Perl script. This is what I came up with:

stopwatch();       # Start the stopwatch
$x  = some_slow_code();
$ms = stopwatch(); # Return milliseconds since start
# Stopwatch function: returns milliseconds
sub stopwatch {
    require Time::HiRes;
    state $start = 0;

    if (!$start) {
        $start = Time::HiRes::time();
    } else {
        my $ret = (Time::HiRes::time() - $start) * 1000;
        $start  = 0; # Reset the start time

        $ret = int($ret);

        return $ret;
    }
}

See also: micros()

Tags:
All content licensed under the Creative Commons License