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

long absdiff(long x, long y);
/*{
    long result;
    if (x < y)
        result = y - x;
    else
        result = x - y;
    return result;
}*/

long cmovdiff(long x, long y);
/*{
    long rval = y-x;
    long eval = x-y;
    long ntest = x >= y;
    if (ntest) rval = eval;
    return rval;
}*/

long clockticks();

long readint(FILE *fp)
{
    // reads 8 bytes into an int
    long n = fgetc(fp);
    n = (n << 8) + fgetc(fp);
    n = (n << 8) + fgetc(fp);
    n = (n << 8) + fgetc(fp);
    n = (n << 8) + fgetc(fp);
    n = (n << 8) + fgetc(fp);
    n = (n << 8) + fgetc(fp);
    n = (n << 8) + fgetc(fp);
    return n;
}
int main(int argc, char **argv)
{
    // argv[1] is a count
    // argv[2] is either 'a' or 'c' (for absdiff or cmovdiff)
    if (argc < 3) {
        printf("usage:\n\t%s count [ac] < [/dev/urandom or /dev/zero]\n",argv[0]);
        printf("example:\n\t%s 1000 a < /dev/urandom\n",argv[0]);
        printf("\t(run 1000 times on absdiff with random input)\n");
        return -1;
    }
    FILE *fp = stdin;
    long x,y;
    long z;

    int count = atoi(argv[1]);

    long avg_ticks = 0;
    long sum_ticks = 0;
    if (*argv[2] == 'a') {
        for (int i = 0; i < count; i++) {
            x = readint(fp);
            y = readint(fp);
            long startTicks = clockticks();
            z = absdiff(x,y);
            long endTicks = clockticks();
            sum_ticks += (endTicks - startTicks); 
        } 
    } else {
        for (int i = 0; i < count; i++) {
            x = readint(fp);
            y = readint(fp);
            long startTicks = clockticks();
            z = cmovdiff(x,y);
            long endTicks = clockticks();
            sum_ticks += (endTicks - startTicks); 
        } 
    }
    avg_ticks = sum_ticks / count;
    printf("last z:%lu\n",z);
    printf("avg ticks:%lu\n",avg_ticks);
    return 0;
}
