Thread Katastrophe Threads (16 answers)
Opened by PerlNoob5 at 2018-09-06 11:19

Linuxer
 2018-09-06 22:56
#188903 #188903
User since
2006-01-27
3875 Artikel
HausmeisterIn

user image
Ich habe mal einen Benchmark gemacht, um die verschiedenen Varianten des Kopierens zu vergleichen.

Das Test-Skript erstellt zunächst einen Ursprungs-Array mit 1.000 Elementen, jedes Element ein zufälliger 20-Zeichen-String.

Getestet habe ich mit den Perl-Versionen 5.22.0, 5.22.4, 5.24.1, 5.24.2, 5.26.1 und bei allen ist das Ergebnis ähnlich (leichte Varianzen in den Zahlen, aber immer gleiche Rangfolge). Ältere Versionen als 5.22.0 habe ich hier nicht installiert, daher keine Tests dafür.

Hier das Ergebnis exemplarisch für 5.26.1:
Code: (dl )
1
2
3
4
5
6
7
8
perl-5.26.1
==========
Rate copy_c_loop copy_c_loop_push copy_foreach copy_foreach_push copy_direct
copy_c_loop 6515/s -- -4% -24% -38% -64%
copy_c_loop_push 6761/s 4% -- -21% -35% -63%
copy_foreach 8532/s 31% 26% -- -18% -53%
copy_foreach_push 10438/s 60% 54% 22% -- -42%
copy_direct 18101/s 178% 168% 112% 73% --


Das schnellste Kopieren ist die direkte Kopie, gefolgt von der foreach-Schleife, in der die Elemente mit push() ins neue Array übertragen werden. Die C-for-Schleife schneidet sogar am schlechtesten ab. Hätte ich so nicht erwartet, muss ich zugeben.



more (14.0kb):

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

use 5.020;
#use Getopt::Long;
use Benchmark qw( cmpthese );


use constant {
    ELEMENTS    => 1_000,
    ELEM_LEN    => 20,
    CHARACTERS  => [ 'a' .. 'z', 'A' .. 'Z', 0 .. 9 ],
};




#> sub routines
#> --------------------------------------------------------------------


sub fill_array {
    my $aRef = shift;
    my $chars = CHARACTERS;
    for ( my $i = 0; $i < ELEMENTS; $i++ ) {
        my $str;
        $str .= $chars->[ rand( @{$chars} ) ]   for 1 .. ELEM_LEN;
        push @$aRef, $str;
    }
}


sub main {

    fill_array( \my @original );

    cmpthese( -1, {
        copy_direct       => sub { my @copy = @original; },
        copy_c_loop       => sub { my @copy; for ( my $i=0; $i<@original; $i++ ) { $copy[$i] = $original[$i] }; },
        copy_c_loop_push  => sub { my @copy; for ( my $i=0; $i<@original; $i++ ) { push @copy, $original[$i] }; },
        copy_foreach      => sub { my @copy; my $i = 0; for my $e ( @original ) { $copy[$i++] = $e; }; },
        copy_foreach_push => sub { my @copy; for my $e ( @original ) { push @copy, $e; }; },
    });

};

#> main programm
#> --------------------------------------------------------------------

main();


__END__

meine Beiträge: I.d.R. alle Angaben ohne Gewähr und auf Linux abgestimmt!
Die Sprache heisst Perl, nicht PERL. - Bitte Crossposts als solche kenntlich machen!

View full thread Katastrophe Threads