I recently needed a small script to report on the number of open files that matched a particular name (in the example, file_a). The platform is AIX, and I decided to make use of the lsof command.

I thought of two easy ways to do this, I could make a single system call to do this: system(lsof -c file_a | wc -l), or, I could get the result of lsof and then use Perl's grep function to get the same sort of count.

I thought that using Perl's grep function would be quicker - but found that doing all of the work via external commands a single system call benchmarked much, much faster.

Can any elightened monks out there tell me why the processing in this example via the external command system call is faster than using the perl functions? I'm still learning Perl, and I've never used the Benchmark module before - so it's entirely possible I made some kind of boneheaded error... Thanks!
#!/usr/bin/perl -w use Benchmark qw(:all) ; use strict; my $lsofcmd1 = "/usr/local/bin/lsof -c file_a|wc -l"; my $lsofcmd2 = "/usr/local/bin/lsof|grep file_a|wc -l"; my $lsofcmd3 = "/usr/local/bin/lsof"; my $count = "500"; my $results = timethese($count, { 'lsof_c' => sub { system($lsofcmd1); }, 'lsof_grep' => sub { system($lsofcmd2); }, 'lsof_perl' => sub { my @ret = `$lsofcmd3`; print scalar(my @openfiles = grep(/fi +le_a/,@ret)); }, }, 'none' ); cmpthese( $results ) ; ##### Results #### # Rate lsof_perl lsof_grep lsof_c # lsof_perl 13.4/s -- -96% -96% # lsof_grep 321/s 2293% -- -5% # lsof_c 338/s 2422% 5% --
Update 1: removed redundant use statements... Update 2: replaced erroneous mentions of system calls - thanks to Errto's response.

In reply to system calls vs perl functions: Which should be faster in this example? by machinecraig

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.