#!/usr/bin/perl use strict; use warnings; use Benchmark::Forking qw( timethese cmpthese ); # UnixOS # use Benchmark qw(:all) ; # WindowsOS my @preserved = @ARGV; sub test_grep { @ARGV = @preserved; # restore original @ARGV my @matched = grep { $_ =~ /AGGT/ } <>; my $count; if (@matched) { for(@matched) { chomp $_; $count .= length($_) . " ";} } close ARGV if eof; } sub test_while { @ARGV = @preserved; # restore original @ARGV my $count; while (<>) { if ($_ =~ /AGGT/){ chomp; $count .= length($_) . " "; } } continue { close ARGV if eof; # reset $. each file } } my $results = timethese(10000000, { Grep => \&test_grep, While => \&test_while }, 'none'); cmpthese( $results ); __DATA__ perl test.pl test.txt Rate Grep While Grep 144175/s -- -21% While 182882/s 27% --