Home > doc > benchmark > primes 
 en fr de es it nl pl pt pt_BR mk sq ca hu tr ar fa id vi ko ja ru zh zh_TW eo
Previous  Next  Edit  Rename  Undo  Search  Administration  
Documentation  
Warning! This page is not translated.  See english version 
Primes
This benchmark computes all prime numbers lower than 10000000. It is repeated ten times.

Results

The execution time is the user time added to the system time, as returned by the bash "time" command.

Python Perl Gambas Gambas + JIT
Execution time (s) 27.6 43.0 20.4 5.95
vs. Python 1 1.56 0.74 0.22
vs. Perl 0.64 1 0.47 0.14
vs. Gambas 1.35 2.11 1 0.29
vs. Gambas + JIT 4.64 7.23 3.43 1

Python source code

#!/usr/bin/python

def get_primes(n):
    if n < 2:  return []
    if n == 2: return [2]
    # do only odd numbers starting at 3
    s = range(3, n+1, 2)
    # n**0.5 simpler than 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)

Perl source code

#!/usr/bin/perl -w

use strict;
use warnings;

sub get_primes($)
{
    my ($n) = @_;

    if ($n < 2) { return (); }
    if ($n == 2) { return (2); }
    # do only odd numbers starting at 3
    my @s = ();
    for (my $i = 3; $i < $n + 1; $i += 2) {
        push(@s, $i);
    }
    # n**0.5 simpler than 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";
}

Gambas source code

#!/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