Thread Performance bei Suche in Hashkeys (14 answers)
Opened by bianca at 2011-02-26 14:30

FIFO
 2011-02-27 21:05
#146095 #146095
User since
2005-06-01
469 Artikel
BenutzerIn

user image
Die Größe Deines Hashes kann ja nicht sehr bedeutend sein, max. 366 keys pro Jahr ... bei einem etwas größeren Hash macht sich der Unterschied schon bei relativ wenigen Zugriffen erheblich bemerkbar:

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
#!/usr/bin/perl -w
use strict;
use warnings;

use List::Util qw(first);
use Benchmark;

my %test;
for my $j (1970..2020) {
    for my $m (1..12) {
        for my $t (1..31) {
            my $d = sprintf '%02d.%02d.%d', $t, $m, $j;
            $test{$d}++;
        }
    }
}

my %found;

my $m_grep = sub {
    foreach my $m (1..12) {
        if (grep { /\.0?$m\./ } keys %test) {
            $found{$m} ||= 1;
        }
    }
};

my $m_first = sub {
    foreach my $m (1..12) {
        if (first { /\.0?$m\./ } keys %test) {
            $found{$m} ||= 1;
        }
    }
};

my $m_pq = sub {
    my %notfound;
    @notfound{1..12} = ();
    my $re = join "|", keys %notfound;
    for my $key (keys %test) {
        if ($key =~ m/\.0?($re)\./) {
            my $month = $1 + 0;
            $found{$month} ||= 1;
            delete $notfound{$month};
            $re = join "|", keys %notfound;
            # wenn alle gefunden, braucht man gar nicht mehr suchen
            last unless keys %notfound;
        }
    }
};

timethese(100, {
    'grep'  => $m_grep,
    'first' => $m_first,
    'pq'    => $m_pq
});


Code: (dl )
1
2
3
4
Benchmark: timing 100 iterations of first, grep, pq...
first: 13 wallclock secs (13.55 usr + 0.00 sys = 13.55 CPU) @ 7.38/s (n=100)
grep: 59 wallclock secs (58.09 usr + 0.17 sys = 58.27 CPU) @ 1.72/s (n=100)
pq: 1 wallclock secs ( 0.86 usr + 0.00 sys = 0.86 CPU) @ 116.41/s (n=100)
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? -- Brian Kernighan: "The Elements of Programming Style"

View full thread Performance bei Suche in Hashkeys