in reply to Re: unbuffered read from socket
in thread unbuffered read from socket
I do think reading one character at a time is your best bet
It's generally poor form and very slow to read one char at a time with sysread(); it's unbuffered, as is C's read(), so you're making a system call per character. Ouch. If you ask for 1024 bytes and only one is available, it will be returned in $buf, sysread returning the number of chars actually read. For example:
my $buf; my $nread; open(my $filehandle, '<', 'f.tmp') or die "error open: $!"; while ($nread = sysread($filehandle, $buf, 1024)) { print "nread=$nread buf='$buf'\n"; }
To illustrate my point, this program:
takes 27 seconds to copy file f.tmp to g.tmp, where f.tmp is perl-5.8.6.tar.gz (about 12 MB). If you simply change:use strict; my $buf; my $nread; open(my $filehandle, '<', 'f.tmp') or die "error open f.tmp: $!"; binmode($filehandle); open(my $fhout, '>', 'g.tmp') or die "error open g.tmp: $!"; binmode($fhout); while ($nread = sysread($filehandle, $buf, 1)) { print $fhout $buf; } close($filehandle); close($fhout);
above to:sysread($filehandle, $buf, 1)
the time reduces to 0.2 seconds.sysread($filehandle, $buf, 1024)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: unbuffered read from socket
by Errto (Vicar) on Dec 29, 2004 at 04:02 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 29, 2004 at 04:35 UTC | |
by Errto (Vicar) on Dec 29, 2004 at 05:03 UTC | |
by Forsaken (Friar) on Dec 29, 2004 at 11:18 UTC |