/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define ACCESS(T) \
void access_##T(int n, int rep) \
{ \
    time_t t1,t2; \
    T *p; \
    int i, j; \
    p = (T *)malloc(n*sizeof(T)); \
    for(i = 0; i < n; i++) p[i] = i % 2; \
    t1 = time(NULL); \
    for(j = 0; j < rep; j++) \
        for(i = 0; i < n; i++) \
            if(p[i] != i % 2) \
                printf("Ooops\n"); \
    t2 = time(NULL); \
    printf("Access %s array size %d : %d seconds\n", #T, n, t2 - t1); \
    free(p); \
}
ACCESS(char)
ACCESS(int)

#define OPS(T) \
void ops_##T(int n, int rep) \
{ \
    time_t t1,t2; \
    T *p; \
    int i, j; \
    p = (T *)malloc(n*sizeof(T)); \
    for(i = 0; i < n; i++) p[i] = i % 2; \
    t1 = time(NULL); \
    for(j = 0; j < rep; j++) \
        for(i = 2; i < n; i++) \
            p[i] = p[i] && p[i-1] || p[i-2]; \
    t2 = time(NULL); \
    printf("Operations %s array size %d : %d seconds\n", #T, n, t2 - t1); \
    free(p); \
}
OPS(char)
OPS(int)

#define N 10000000
#define SIEVE(T) \
void sieve_##T() \
{ \
    time_t t1,t2; \
    T *p; \
    int i, j; \
    p = (T *)malloc(N*sizeof(T)); \
    for(i = 0; i < N; i++) p[i] = 1; \
    t1 = time(NULL); \
    for(i = 2; i < N; i++) \
        for(j = 2*i; j < N; j=j+i) \
            p[j] = 0; \
    t2 = time(NULL); \
    printf("Sieve %s array size %d : %d seconds\n", #T, N, t2 - t1); \
    free(p); \
}
SIEVE(char)
SIEVE(int)

int main()
{
    access_char(100, 100000000);
    access_int(100, 100000000);
    access_char(10000, 1000000);
    access_int(10000, 1000000);
    access_char(1000000, 10000);
    access_int(1000000, 10000);
    access_char(100000000, 100);
    access_int(100000000, 100);
    ops_char(100, 100000000);
    ops_int(100, 100000000);
    ops_char(10000, 1000000);
    ops_int(10000, 1000000);
    ops_char(1000000, 10000);
    ops_int(1000000, 10000);
    ops_char(100000000, 100);
    ops_int(100000000, 100);
    sieve_char();
    sieve_int();
    return 0;
}
