aboutsummaryrefslogtreecommitdiffstats
path: root/test/c/nsieve.c
blob: 83e1e1f03ca3b69a2545ecbe5b52c4bd9f242fd8 (plain)
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
// The Computer Language Shootout
// http://shootout.alioth.debian.org/
// Precedent C entry modified by bearophile for speed and size, 31 Jan 2006
// Compile with:  -O3 -s -std=c99 -fomit-frame-pointer

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef unsigned char boolean;


static unsigned int nsieve(int m) {
    unsigned int count = 0, i, j;
    boolean * flags = (boolean *) malloc(m * sizeof(boolean));
    memset(flags, 1, m);

    for (i = 2; i < m; ++i)
        if (flags[i]) {
            ++count;
            for (j = i << 1; j < m; j += i)
                if (flags[j]) flags[j] = 0;
    }

    free(flags);
    return count;
}

#define NITER 2

int main(int argc, char * argv[]) {
#ifdef __KVX__
    int m = argc < 2 ? 6 : atoi(argv[1]);
#else
    int m = argc < 2 ? 9 : atoi(argv[1]);
#endif
    int i, j;
    for (i = 0; i < 3; i++) {
#ifdef __KVX__
      int n = 200 << (m-i);
#else
      int n = 10000 << (m-i);
#endif
      unsigned count;
      for (j = 0; j < NITER; j++) { count = nsieve(n); }
      printf("Primes up to %8d %8u\n", n, count);
    }
    return 0;
}

/********
 build & benchmark results

BUILD COMMANDS FOR: nsieve.gcc

Thu Sep 14 20:51:46 PDT 2006

/usr/bin/gcc -pipe -Wall -O3 -fomit-frame-pointer -funroll-loops -march=pentium4 -s -std=c99 nsieve.c -o nsieve.gcc_run

=================================================================
COMMAND LINE (%A is single numeric argument):

nsieve.gcc_run %A
N=9

PROGRAM OUTPUT
==============
Primes up to  5120000   356244
Primes up to  2560000   187134
Primes up to  1280000    98610
*******/