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

Hi,
Is there any way to get finer timing output than Time::HiRes, say upto nano/milisecond?. My code below:
#!/usr/bin/perl -w use Time::HiRes qw(clock); # version 1.90 my $start_time = clock(); $line++ while (<>); # Count number of lines in the file(s) my $end_time = clock(); my $difference = $end_time - $start_time; print ("It took ", $difference, " second\n");
Gives:
It took 0.02 second
Which is not refined enough to me.

Replies are listed 'Best First'.
Re: More Detailed Timing than Time::HiRes' clock method
by liverpole (Monsignor) on Sep 26, 2006 at 12:43 UTC
    How about using tv_interval? ...
    #!/usr/bin/perl -w use strict; use warnings; use Time::HiRes qw( gettimeofday tv_interval ); my $start = [gettimeofday]; my $line; $line++ while (<>); # Count number of lines in the file(s) my $end = [gettimeofday]; my $difference = tv_interval($start, $end); print "It took ", $difference, " second\n";

    which gives something like:

    It took 0.000103 second

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: More Detailed Timing than Time::HiRes' clock method
by McDarren (Abbot) on Sep 26, 2006 at 12:50 UTC
    Have you even looked at the documentation for Time::HiRes?

    $your_code =~ s/clock/time/g;

    ...and then you should get something like:

    perl nano foo.pl It took 0.01027512550354 second
      McDarren,
      How can you use 'nano' there? Cause when I followed your suggestion and calling 'nano' it gives me:
      Can't open perl script "nano": No such file or directory.
      Nevertheless, without nano it prints the refined results though.

      BTW also, what is the difference between time() as used by you versus liverpole's suggestion of using 'tv_interval' and 'gettimeofday'?
        "How can you use 'nano' there?..."

        I think perhaps my example was a little misleading. "nano" is the name of the script, and "foo.pl" is the name of the file being precessed. Think of it instead as:

        perl nano some_random_file
        ..and it should make more sense.

        "..what is the difference between time() as used by you versus liverpole's suggestion of using 'tv_interval' and 'gettimeofday'?"

        Again, rtfm. As far as I can see, there is no real difference. The resolution that you get will be mostly system-dependant.

        Cheers,
        Darren