Thread Testen, ob variable eine Zahl ist (21 answers)
Opened by pktm at 2010-02-22 23:21

topeg
 2010-02-23 01:51
#133503 #133503
User since
2006-07-10
2611 Artikel
BenutzerIn

user image
Ein paar Benchmarks:

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/perl

use strict;
use warnings;
use Benchmark qw(cmpthese);

my %tests=(
  '6407587026'=>1,
  '97698bhj767565'=>0,
  '7867854jh6546789'=>0,
  '86565'=>1,
  '54587'=>1,
  'ghggftr'=>0,
  '557765547'=>1,
  'g569876876'=>0,
  '656778z6565'=>0,
  '6578867ggh7'=>0,
  '54tf5945'=>0,
  '67556567'=>1,
  '765476'=>1,
  '*Ä?=()&§9§""¹³¹²³½[}\¼'=>0,
  '454564'=>1,
  '547989'=>1,
  '709'=>1,
  '=)(/(&$§"%%/)(=/(/'=>0,
);
my @zahlen=keys(%tests);

my %functs=(
  'split1'=>\&test_of_number_a,
  'split2'=>\&test_of_number_b,
  'regexp'=>\&test_of_number_c,
  '   int'=>\&test_of_number_d,
  'unpack'=>\&test_of_number_e,
  '    tr'=>\&test_of_number_f,
);

while( my ($name,$func)=each(%functs))
{
  my $ok=1;
  while(my ($num,$res)=each(%tests))
  {
    $ok=0 if($func->($num)!=$res);
  }
  print "$name => ",$ok?'OK':'FAILED',"\n";
  $functs{$name}=sub{ $func->($_) for(@zahlen); };
}
cmpthese(40000,\%functs);

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

sub test_of_number_a
{
  for my $pos (0..length($_[0])-1)
  {
    $_=ord(substr($_[0],$pos,1));
    return 0 if($_<48 || 57<$_);
  }
  return 1;
}

sub test_of_number_b
{
  for(split('',''.shift()))
  {
    $_=ord($_);
    return 0 if($_<48 || 57<$_);
  }
  return 1;
}

sub test_of_number_c
{
  return 1 if($_[0]=~/^\d+$/);
  return 0;
}

sub test_of_number_d
{
  no warnings;
  return 1 if(int($_[0]) eq $_[0]);
  return 0;
}

sub test_of_number_e
{
  ($_<48 || 57<$_)?return 0:undef() for(unpack('C*',$_[0]));
  return 1;
}

sub test_of_number_f
{
  return 1 if($_[0]=~ y/0-9// == length($_[0]));
  return 0;
}


Code: (dl )
1
2
3
4
5
6
7
          Rate split2 split1 unpack regexp    int     tr
split2 12308/s -- -8% -32% -66% -68% -72%
split1 13423/s 9% -- -26% -63% -65% -69%
unpack 18100/s 47% 35% -- -50% -52% -59%
regexp 36036/s 193% 168% 99% -- -5% -18%
int 38095/s 210% 184% 110% 6% -- -13%
tr 43956/s 257% 227% 143% 22% 15% --


"tr"/"y" scheint mit Abstand das schnellste zu sein.

EDIT: Zeile 87 korrigiert
Last edited: 2010-02-23 10:46:48 +0100 (CET)

View full thread Testen, ob variable eine Zahl ist