On Tue, Apr 14, 2009 at 11:49, Rick <rich.j...@gmail.com> wrote:
> is it true that perl will be just as fast as c for reading files ?
>
> for example
>
> will  below be as fast as if it were written in c?
> I said this because on random posts, I see that perl is optimized to work w/
> text files and it should be as fast as perl
>
> open FILE, $file or die "bad filename: $!";
>  while (my $line = <FILE>) {
>         #do something w $line
>  }
snip

Why not test it?
With the file already in the filesystem's read-ahead buffer

cow...@amans:~$ time cat /usr/share/dict/words | perl wc.pl
234936

real    0m0.083s
user    0m0.062s
sys     0m0.015s
cow...@amans:~$ time cat /usr/share/dict/words | ./wc
234936

real    0m0.028s
user    0m0.013s
sys     0m0.012s

You can decide whether the .04 seconds is worth the extra time it
takes to write the C code.

#include <stdio.h>

int main (int argc, char** argv) {
        char   buf[4096];
        size_t i;
        size_t bytes;
        size_t count = 0;

        while (bytes = fread(buf, 1, 4096, stdin))
                for (i = 0; i < bytes; i++)
                        if (buf[i] == '\n')
                                count++;

        printf("%d\n", count);

        return 0;
}

#!/usr/bin/perl

use strict;
use warnings;

my $count = 0;

$/ = \4096;
while (<>) {
        $count += tr/\n//;
}

print "$count\n";



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to