Thread Problem mit FileHandle (24 answers)
Opened by rosti at 2011-04-05 22:27

topeg
 2011-04-06 11:36
#147415 #147415
User since
2006-07-10
2611 Artikel
BenutzerIn

user image
Teste es:
more (17.9kb):
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/perl
use strict;
use warnings;
use IO::File;
use Fcntl ':flock';
use Storable;
use Benchmark 'cmpthese';

my $data={ map{join('',map{chr(rand(26)+65)}(0..rand(30))) => int(rand(400))}(0..100) };
my $file1="storage_test_a.bin";
my $file2="storage_test_b.bin";

########################################################################
unlink($file1);
unlink($file2);

cmpthese(10_000, {
  'store'     => sub { store($data, $file1); unlink($file1), },
  'serialize' => sub { serialize($file2,$data); unlink($file2); },
});

########################################################################
store($data, $file1);
serialize($file2,$data);

cmpthese(10_000, {
  'retrieve'    => sub { retrieve($file1); },
  'deserialize' => sub { deserialize($file2); },
});

########################################################################
########################################################################
########################################################################

# hash to file
sub serialize{
        my ($file,$data)=@_;
        my $fh=IO::File->new($file, O_CREAT|O_BINARY|O_RDWR) or die("ERROR open $file ($!)\n");
        if(defined $fh){
                truncate $fh, 0;
                seek $fh, 0, 0;
                while(my ($k, $v) = each %$data){
                        print $fh pack("N", length $k).$k.pack("N", $v);
                }
        }
}

# hash from $file
sub deserialize{
        my $file = shift;
        my %rep;
        my $fh=IO::File->new($file, O_CREAT|O_BINARY|O_RDWR) or die("ERROR open $file ($!)\n");
        flock($fh, LOCK_EX) or die "Your system does not support flock()!";
        binmode $fh, ':raw';
        seek $fh, 0, 0;
        my ($buffer, $key, $klen, $number) = (undef, undef, undef, undef);
        while(read $fh, $buffer, 4){
                $klen = unpack "N", $buffer;
                read $fh, $key, $klen;
                read $fh, $buffer, 4;
                $rep{$key} = unpack "N", $buffer;
        }
        return \%rep;
}

bei mir:
Code: (dl )
1
2
3
4
5
6
            Rate serialize     store
serialize 3704/s -- -48%
store 7143/s 93% --
Rate deserialize retrieve
deserialize 3448/s -- -61%
retrieve 8929/s 159% --

View full thread Problem mit FileHandle