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

Hello,
Need advice why shared memory is so slow. My assumption was that shared memory is like usual memory. But this simple test show contrary.
I guess that my test is bad...
#!/usr/bin/evn perl
use strict;
use warnings;

use Benchmark qw(:all :hireswallclock);
use IPC::SysV qw(IPC_CREAT);
use Data::Dumper::Concise;

my $data;
my $size = 65536;

my $id = shmget('12345', $size, IPC_CREAT | 0666);

my $mem = join('', map { ('a' .. 'z')rand(26) } (1..65536));
open(MEMORY, "<", \$mem);

shmwrite( $id, $mem, 0, $size );

cmpthese( -1, {
    'shmread'     => sub { shmread( $id, $data, 0, $size ) || die "shmread: $!" },
    'memory read' => sub { read( MEMORY, $data, $size, 0 ) // die "read: $!" },
});
$ perl bin/test/bench/shmread.pl 
                  Rate     shmread memory read
shmread        36202/s          --       -100%
memory read 10155128/s      27951%          --

Replies are listed 'Best First'.
Re: Slow shared memory issue
by Anonymous Monk on Mar 27, 2016 at 17:00 UTC
    You have to check the return value of sysread, like so
    'memory read' => sub { sysread( MEMORY, $data, 0, $size ) // die $!; }
    you'll see 'Bad file descriptor'. sysread cannot read from a filehandle opened on a string; it needs a real file descriptor. Also, you probably meant sysread( MEMORY, $data, $size, 0 ) (the third argument is the number of bytes to read and the fourth is offset - thats different from shmread).

    shmread will probably still be slower, since it reads or writes the System V shared memory segment... by attaching to it, copying in/out, and detaching from it.

      shmat (attach) -> memread (read) works 8x times faster

      So now I have only one question. Why IPC::Shareable do not uses benefits of shmat -> memread flow ? It uses shmread which is obviously slow...

      https://metacpan.org/source/MSOUTH/IPC-Shareable-0.61/lib/IPC/Shareable/SharedMem.pm#L97
      You're right... missed errors checks.

      Thank you for the answer about attaching to shared segment. It's quite expensive operation. It clarify performance issue.

      Don't understand why there is no description - http://perldoc.perl.org/functions/shmread.html