Primes
Ce comparatif de performances calcule tous les nombres premiers plus petits que 10000000. Il est répété dix fois.
Resultats
La durée d'éxécution est le temps utilisateur ajouté au temps système, comme la renvoie la commande "time" de bash.
|
Python
|
Perl
|
Gambas
|
Durée d'éxécution
|
27.6s
|
43.0 s
|
20.4 s
|
vs. Python
|
100 %
|
156 %
|
74 %
|
vs. Perl
|
64 %
|
100 %
|
47 %
|
vs. Gambas
|
135 %
|
211 %
|
100 %
|
Code source Python
#!/usr/bin/python
def get_primes(n):
if n < 2: return []
if n == 2: return [2]
# ne traiter que les nombres impairs à partir de 3
s = range(3, n+1, 2)
# n**0.5 plus simple que math.sqr(n)
mroot = n ** 0.5
half = len(s)
i = 0
m = 3
while m <= mroot:
if s[i]:
j = (m*m-3)//2 # int div
s[j] = 0
while j < half:
s[j] = 0
j += m
i = i+1
m = 2*i+3
return [2]+[x for x in s if x]
for t in range(10):
res = get_primes(10000000)
print len(res)
Code source Perl
#!/usr/bin/perl -w
use strict;
use warnings;
sub get_primes($)
\{
my ($n) = @_;
if ($n < 2) { return (); }
if ($n == 2) { return (2); }
# ne traiter que les nombres impairs à partir de 3
my @s = ();
for (my $i = 3; $i < $n + 1; $i += 2) {
push(@s, $i);
}
# n**0.5 plus simple que math.sqr(n)
my $mroot = $n ** 0.5;
my $half = scalar @s;
my $i = 0;
my $m = 3;
while ($m <= $mroot) {
if ($s[$i]) {
my $j = int(($m*$m - 3) / 2);
$s[$j] = 0;
while ($j < $half) {
$s[$j] = 0;
$j += $m;
}
}
$i = $i + 1;
$m = 2*$i + 3;
}
my @res = (2);
foreach (@s) {
push(@res, $_) if ($_);
}
return @res;
}
my @res;
for (1..10) {
@res = get_primes(10000000);
print scalar @res; print "\n";
}
Code source Gambas
#!/usr/bin/env gbs3
Sub GetPrimes(N As Integer) As Integer[]
Dim aRes As New Integer[]
Dim S As Integer[]
Dim I, J, M As Integer
Dim iMRoot, iHalf As Integer
If N < 2 Then Return aRes
If N = 2 Then Return [ 2 ]
S = New Integer[(N - 3 + 1) \ 2]
For J = 3 To N Step 2
S[I] = J
Inc I
Next
iMRoot = Sqr(N)
iHalf = S.Count
I = 0
M = 3
While M <= iMRoot
If S[I] Then
J = (M * M - 3) \ 2
S[J] = 0
While J < iHalf
S[J] = 0
J += M
Wend
Endif
Inc I
M = 2 * I + 3
Wend
aRes.Add(2)
For Each I In S
If I Then aRes.Add(I)
Next
Return aRes
End
Dim aRes As Integer[]
Dim I As Integer
For I = 1 To 10
aRes = GetPrimes(10000000)
Print aRes.Count
Next