High-Resolution Timers

Problem

You need to measure time with a finer granularity than the full seconds that time returns.

Solution

This might not be possible. If your system supports both the syscall function in Perl as well as a system call like gettimeofday(2), then you could possibly use them to measure the time. The procedure for using syscall varies from system to system. The Discussion has sample code using it, but this is not necessarily portable.

The Time::HiRes module (available from CPAN) encapsulates this functionality for some systems:

use Time::HiRes qw(gettimeofday);
$t0 = gettimeofday;
## do your operation here
$t1 = gettimeofday;
$elapsed = $t1-$t0;
# $elapsed is a floating point value, representing number
# of seconds between $t0 and $t1

Discussion

Here’s some code that uses Time::HiRes to time how long the user takes to press RETURN:

use Time::HiRes qw(gettimeofday);
print "Press return when ready: ";
$before = gettimeofday;
$line = <>;
$elapsed = gettimeofday-$before;
print "You took $elapsed seconds.\n";

                  Press return when ready: 
               
                  You took 0.228149 seconds.

Compare this to the equivalent syscall code:

require 'sys/syscall.ph'; # initialize the structures returned by gettimeofday $TIMEVAL_T = "LL"; $done = $start = pack($TIMEVAL_T, ()); # prompt print "Press return when ready: "; # read the time into $start syscall(&SYS_gettimeofday, $start, 0) != -1 || die "gettimeofday: $!"; # read a line $line = <>; # read the time into $done syscall(&SYS_gettimeofday, $done, 0) ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.